// Spectrum Colorpicker v1.8.0
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT

(function($, undefined) {
    

    var defaultOpts = {

        // Callbacks
        beforeShow: noop,
        move: noop,
        change: noop,
        show: noop,
        hide: noop,

        // Options
        color: false,
        flat: false,
        showInput: false,
        allowEmpty: false,
        showButtons: true,
        clickoutFiresChange: true,
        showInitial: false,
        showPalette: false,
        showPaletteOnly: false,
        hideAfterPaletteSelect: false,
        togglePaletteOnly: false,
        showSelectionPalette: true,
        localStorageKey: false,
        appendTo: "body",
        maxSelectionSize: 7,
        cancelText: "取消",
        chooseText: "确定",
        togglePaletteMoreText: "more",
        togglePaletteLessText: "less",
        clearText: "Clear Color Selection",
        noColorSelectedText: "No Color Selected",
        preferredFormat: false,
        className: "", // Deprecated - use containerClassName and replacerClassName instead.
        containerClassName: "",
        replacerClassName: "",
        showAlpha: false,
        theme: "sp-light",
        palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]],
        selectionPalette: [],
        disabled: false,
        offset: null
    },
    spectrums = [],
    IE = !!/msie/i.exec( window.navigator.userAgent ),
    rgbaSupport = (function() {
        function contains( str, substr ) {
            return !!~('' + str).indexOf(substr);
        }

        var elem = document.createElement('div');
        var style = elem.style;
        style.cssText = 'background-color:rgba(0,0,0,.5)';
        return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
    })(),
    replaceInput = [
        "<div class='sp-replacer'>",
            "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
            "<div class='sp-dd'>&#9660;</div>",
        "</div>"
    ].join(''),
    markup = (function () {

        // IE does not support gradients with multiple stops, so we need to simulate
        //  that for the rainbow slider with 8 divs that each have a single gradient
        var gradientFix = "";
        if (IE) {
            for (var i = 1; i <= 6; i++) {
                gradientFix += "<div class='sp-" + i + "'></div>";
            }
        }

        return [
            "<div class='sp-container sp-hidden'>",
                "<div class='sp-palette-container'>",
                    "<div class='sp-palette sp-thumb sp-cf'></div>",
                    "<div class='sp-palette-button-container sp-cf'>",
                        "<button type='button' class='sp-palette-toggle'></button>",
                    "</div>",
                "</div>",
                "<div class='sp-picker-container'>",
                    "<div class='sp-top sp-cf'>",
                        "<div class='sp-fill'></div>",
                        "<div class='sp-top-inner'>",
                            "<div class='sp-color'>",
                                "<div class='sp-sat'>",
                                    "<div class='sp-val'>",
                                        "<div class='sp-dragger'></div>",
                                    "</div>",
                                "</div>",
                            "</div>",
                            "<div class='sp-clear sp-clear-display'>",
                            "</div>",
                            "<div class='sp-hue'>",
                                "<div class='sp-slider'></div>",
                                gradientFix,
                            "</div>",
                        "</div>",
                        "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
                    "</div>",
                    "<div class='sp-input-container sp-cf'>",
                        "<input class='sp-input' type='text' spellcheck='false'  />",
                    "</div>",
                    "<div class='sp-initial sp-thumb sp-cf'></div>",
                    "<div class='sp-button-container sp-cf'>",
                        "<a class='sp-cancel' href='#'></a>",
                        "<button type='button' class='sp-choose'></button>",
                    "</div>",
                "</div>",
            "</div>"
        ].join("");
    })();

    function paletteTemplate (p, color, className, opts) {
        var html = [];
        for (var i = 0; i < p.length; i++) {
            var current = p[i];
            if(current) {
                var tiny = tinycolor(current);
                var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
                c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
                var formattedString = tiny.toString(opts.preferredFormat || "rgb");
                var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
                html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';" /></span>');
            } else {
                var cls = 'sp-clear-display';
                html.push($('<div />')
                    .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>')
                        .attr('title', opts.noColorSelectedText)
                    )
                    .html()
                );
            }
        }
        return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
    }

    function hideAll() {
        for (var i = 0; i < spectrums.length; i++) {
            if (spectrums[i]) {
                spectrums[i].hide();
            }
        }
    }

    function instanceOptions(o, callbackContext) {
        var opts = $.extend({}, defaultOpts, o);
        opts.callbacks = {
            'move': bind(opts.move, callbackContext),
            'change': bind(opts.change, callbackContext),
            'show': bind(opts.show, callbackContext),
            'hide': bind(opts.hide, callbackContext),
            'beforeShow': bind(opts.beforeShow, callbackContext)
        };

        return opts;
    }

    function spectrum(element, o) {

        var opts = instanceOptions(o, element),
            flat = opts.flat,
            showSelectionPalette = opts.showSelectionPalette,
            localStorageKey = opts.localStorageKey,
            theme = opts.theme,
            callbacks = opts.callbacks,
            resize = throttle(reflow, 10),
            visible = false,
            isDragging = false,
            dragWidth = 0,
            dragHeight = 0,
            dragHelperHeight = 0,
            slideHeight = 0,
            slideWidth = 0,
            alphaWidth = 0,
            alphaSlideHelperWidth = 0,
            slideHelperHeight = 0,
            currentHue = 0,
            currentSaturation = 0,
            currentValue = 0,
            currentAlpha = 1,
            palette = [],
            paletteArray = [],
            paletteLookup = {},
            selectionPalette = opts.selectionPalette.slice(0),
            maxSelectionSize = opts.maxSelectionSize,
            draggingClass = "sp-dragging",
            shiftMovementDirection = null;

        var doc = element.ownerDocument,
            body = doc.body,
            boundElement = $(element),
            disabled = false,
            container = $(markup, doc).addClass(theme),
            pickerContainer = container.find(".sp-picker-container"),
            dragger = container.find(".sp-color"),
            dragHelper = container.find(".sp-dragger"),
            slider = container.find(".sp-hue"),
            slideHelper = container.find(".sp-slider"),
            alphaSliderInner = container.find(".sp-alpha-inner"),
            alphaSlider = container.find(".sp-alpha"),
            alphaSlideHelper = container.find(".sp-alpha-handle"),
            textInput = container.find(".sp-input"),
            paletteContainer = container.find(".sp-palette"),
            initialColorContainer = container.find(".sp-initial"),
            cancelButton = container.find(".sp-cancel"),
            clearButton = container.find(".sp-clear"),
            chooseButton = container.find(".sp-choose"),
            toggleButton = container.find(".sp-palette-toggle"),
            isInput = boundElement.is("input"),
            isInputTypeColor = isInput && boundElement.attr("type") === "color" && inputTypeColorSupport(),
            shouldReplace = isInput && !flat,
            replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]),
            offsetElement = (shouldReplace) ? replacer : boundElement,
            previewElement = replacer.find(".sp-preview-inner"),
            initialColor = opts.color || (isInput && boundElement.val()),
            colorOnShow = false,
            currentPreferredFormat = opts.preferredFormat,
            clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
            isEmpty = !initialColor,
            allowEmpty = opts.allowEmpty && !isInputTypeColor;

        function applyOptions() {

            if (opts.showPaletteOnly) {
                opts.showPalette = true;
            }

            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);

            if (opts.palette) {
                palette = opts.palette.slice(0);
                paletteArray = $.isArray(palette[0]) ? palette : [palette];
                paletteLookup = {};
                for (var i = 0; i < paletteArray.length; i++) {
                    for (var j = 0; j < paletteArray[i].length; j++) {
                        var rgb = tinycolor(paletteArray[i][j]).toRgbString();
                        paletteLookup[rgb] = true;
                    }
                }
            }

            container.toggleClass("sp-flat", flat);
            container.toggleClass("sp-input-disabled", !opts.showInput);
            container.toggleClass("sp-alpha-enabled", opts.showAlpha);
            container.toggleClass("sp-clear-enabled", allowEmpty);
            container.toggleClass("sp-buttons-disabled", !opts.showButtons);
            container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly);
            container.toggleClass("sp-palette-disabled", !opts.showPalette);
            container.toggleClass("sp-palette-only", opts.showPaletteOnly);
            container.toggleClass("sp-initial-disabled", !opts.showInitial);
            container.addClass(opts.className).addClass(opts.containerClassName);

            reflow();
        }

        function initialize() {

            if (IE) {
                container.find("*:not(input)").attr("unselectable", "on");
            }

            applyOptions();

            if (shouldReplace) {
                boundElement.after(replacer).hide();
            }

            if (!allowEmpty) {
                clearButton.hide();
            }

            if (flat) {
                boundElement.after(container).hide();
            }
            else {

                var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
                if (appendTo.length !== 1) {
                    appendTo = $("body");
                }

                appendTo.append(container);
            }

            updateSelectionPaletteFromStorage();

            offsetElement.bind("click.spectrum touchstart.spectrum", function (e) {
                if (!disabled) {
                    toggle();
                }

                e.stopPropagation();

                if (!$(e.target).is("input")) {
                    e.preventDefault();
                }
            });

            if(boundElement.is(":disabled") || (opts.disabled === true)) {
                disable();
            }

            // Prevent clicks from bubbling up to document.  This would cause it to be hidden.
            container.click(stopPropagation);

            // Handle user typed input
            textInput.change(setFromTextInput);
            textInput.bind("paste", function () {
                setTimeout(setFromTextInput, 1);
            });
            textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });

            cancelButton.text(opts.cancelText);
            cancelButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();
                revert();
                hide();
            });

            clearButton.attr("title", opts.clearText);
            clearButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();
                isEmpty = true;
                move();

                if(flat) {
                    //for the flat style, this is a change event
                    updateOriginalInput(true);
                }
            });

            chooseButton.text(opts.chooseText);
            chooseButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();

                if (IE && textInput.is(":focus")) {
                    textInput.trigger('change');
                }

                if (isValid()) {
                    updateOriginalInput(true);
                    hide();
                }
            });

            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
            toggleButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();

                opts.showPaletteOnly = !opts.showPaletteOnly;

                // To make sure the Picker area is drawn on the right, next to the
                // Palette area (and not below the palette), first move the Palette
                // to the left to make space for the picker, plus 5px extra.
                // The 'applyOptions' function puts the whole container back into place
                // and takes care of the button-text and the sp-palette-only CSS class.
                if (!opts.showPaletteOnly && !flat) {
                    container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
                }
                applyOptions();
            });

            draggable(alphaSlider, function (dragX, dragY, e) {
                currentAlpha = (dragX / alphaWidth);
                isEmpty = false;
                if (e.shiftKey) {
                    currentAlpha = Math.round(currentAlpha * 10) / 10;
                }

                move();
            }, dragStart, dragStop);

            draggable(slider, function (dragX, dragY) {
                currentHue = parseFloat(dragY / slideHeight);
                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }
                move();
            }, dragStart, dragStop);

            draggable(dragger, function (dragX, dragY, e) {

                // shift+drag should snap the movement to either the x or y axis.
                if (!e.shiftKey) {
                    shiftMovementDirection = null;
                }
                else if (!shiftMovementDirection) {
                    var oldDragX = currentSaturation * dragWidth;
                    var oldDragY = dragHeight - (currentValue * dragHeight);
                    var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);

                    shiftMovementDirection = furtherFromX ? "x" : "y";
                }

                var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
                var setValue = !shiftMovementDirection || shiftMovementDirection === "y";

                if (setSaturation) {
                    currentSaturation = parseFloat(dragX / dragWidth);
                }
                if (setValue) {
                    currentValue = parseFloat((dragHeight - dragY) / dragHeight);
                }

                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }

                move();

            }, dragStart, dragStop);

            if (!!initialColor) {
                set(initialColor);

                // In case color was black - update the preview UI and set the format
                // since the set function will not run (default color is black).
                updateUI();
                currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).format;

                addColorToSelectionPalette(initialColor);
            }
            else {
                updateUI();
            }

            if (flat) {
                show();
            }

            function paletteElementClick(e) {
                if (e.data && e.data.ignore) {
                    set($(e.target).closest(".sp-thumb-el").data("color"));
                    move();
                }
                else {
                    set($(e.target).closest(".sp-thumb-el").data("color"));
                    move();
                    updateOriginalInput(true);
                    if (opts.hideAfterPaletteSelect) {
                      hide();
                    }
                }

                return false;
            }

            var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
            paletteContainer.delegate(".sp-thumb-el", paletteEvent, paletteElementClick);
            initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, paletteElementClick);
        }

        function updateSelectionPaletteFromStorage() {

            if (localStorageKey && window.localStorage) {

                // Migrate old palettes over to new format.  May want to remove this eventually.
                try {
                    var oldPalette = window.localStorage[localStorageKey].split(",#");
                    if (oldPalette.length > 1) {
                        delete window.localStorage[localStorageKey];
                        $.each(oldPalette, function(i, c) {
                             addColorToSelectionPalette(c);
                        });
                    }
                }
                catch(e) { }

                try {
                    selectionPalette = window.localStorage[localStorageKey].split(";");
                }
                catch (e) { }
            }
        }

        function addColorToSelectionPalette(color) {
            if (showSelectionPalette) {
                var rgb = tinycolor(color).toRgbString();
                if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
                    selectionPalette.push(rgb);
                    while(selectionPalette.length > maxSelectionSize) {
                        selectionPalette.shift();
                    }
                }

                if (localStorageKey && window.localStorage) {
                    try {
                        window.localStorage[localStorageKey] = selectionPalette.join(";");
                    }
                    catch(e) { }
                }
            }
        }

        function getUniqueSelectionPalette() {
            var unique = [];
            if (opts.showPalette) {
                for (var i = 0; i < selectionPalette.length; i++) {
                    var rgb = tinycolor(selectionPalette[i]).toRgbString();

                    if (!paletteLookup[rgb]) {
                        unique.push(selectionPalette[i]);
                    }
                }
            }

            return unique.reverse().slice(0, opts.maxSelectionSize);
        }

        function drawPalette() {

            var currentColor = get();

            var html = $.map(paletteArray, function (palette, i) {
                return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts);
            });

            updateSelectionPaletteFromStorage();

            if (selectionPalette) {
                html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts));
            }

            paletteContainer.html(html.join(""));
        }

        function drawInitial() {
            if (opts.showInitial) {
                var initial = colorOnShow;
                var current = get();
                initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts));
            }
        }

        function dragStart() {
            if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
                reflow();
            }
            isDragging = true;
            container.addClass(draggingClass);
            shiftMovementDirection = null;
            boundElement.trigger('dragstart.spectrum', [ get() ]);
        }

        function dragStop() {
            isDragging = false;
            container.removeClass(draggingClass);
            boundElement.trigger('dragstop.spectrum', [ get() ]);
        }

        function setFromTextInput() {

            var value = textInput.val();

            if ((value === null || value === "") && allowEmpty) {
                set(null);
                updateOriginalInput(true);
            }
            else {
                var tiny = tinycolor(value);
                if (tiny.isValid()) {
                    set(tiny);
                    updateOriginalInput(true);
                }
                else {
                    textInput.addClass("sp-validation-error");
                }
            }
        }

        function toggle() {
            if (visible) {
                hide();
            }
            else {
                show();
            }
        }

        function show() {
            var event = $.Event('beforeShow.spectrum');

            if (visible) {
                reflow();
                return;
            }

            boundElement.trigger(event, [ get() ]);

            if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
                return;
            }

            hideAll();
            visible = true;

            $(doc).bind("keydown.spectrum", onkeydown);
            $(doc).bind("click.spectrum", clickout);
            $(window).bind("resize.spectrum", resize);
            replacer.addClass("sp-active");
            container.removeClass("sp-hidden");

            reflow();
            updateUI();

            colorOnShow = get();

            drawInitial();
            callbacks.show(colorOnShow);
            boundElement.trigger('show.spectrum', [ colorOnShow ]);
        }

        function onkeydown(e) {
            // Close on ESC
            if (e.keyCode === 27) {
                hide();
            }
        }

        function clickout(e) {
            // Return on right click.
            if (e.button == 2) { return; }

            // If a drag event was happening during the mouseup, don't hide
            // on click.
            if (isDragging) { return; }

            if (clickoutFiresChange) {
                updateOriginalInput(true);
            }
            else {
                revert();
            }
            hide();
        }

        function hide() {
            // Return if hiding is unnecessary
            if (!visible || flat) { return; }
            visible = false;

            $(doc).unbind("keydown.spectrum", onkeydown);
            $(doc).unbind("click.spectrum", clickout);
            $(window).unbind("resize.spectrum", resize);

            replacer.removeClass("sp-active");
            container.addClass("sp-hidden");

            callbacks.hide(get());
            boundElement.trigger('hide.spectrum', [ get() ]);
        }

        function revert() {
            set(colorOnShow, true);
        }

        function set(color, ignoreFormatChange) {
            if (tinycolor.equals(color, get())) {
                // Update UI just in case a validation error needs
                // to be cleared.
                updateUI();
                return;
            }

            var newColor, newHsv;
            if (!color && allowEmpty) {
                isEmpty = true;
            } else {
                isEmpty = false;
                newColor = tinycolor(color);
                newHsv = newColor.toHsv();

                currentHue = (newHsv.h % 360) / 360;
                currentSaturation = newHsv.s;
                currentValue = newHsv.v;
                currentAlpha = newHsv.a;
            }
            updateUI();

            if (newColor && newColor.isValid() && !ignoreFormatChange) {
                currentPreferredFormat = opts.preferredFormat || newColor.getFormat();
            }
        }

        function get(opts) {
            opts = opts || { };

            if (allowEmpty && isEmpty) {
                return null;
            }

            return tinycolor.fromRatio({
                h: currentHue,
                s: currentSaturation,
                v: currentValue,
                a: Math.round(currentAlpha * 100) / 100
            }, { format: opts.format || currentPreferredFormat });
        }

        function isValid() {
            return !textInput.hasClass("sp-validation-error");
        }

        function move() {
            updateUI();

            callbacks.move(get());
            boundElement.trigger('move.spectrum', [ get() ]);
        }

        function updateUI() {

            textInput.removeClass("sp-validation-error");

            updateHelperLocations();

            // Update dragger background color (gradients take care of saturation and value).
            var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
            dragger.css("background-color", flatColor.toHexString());

            // Get a format that alpha will be included in (hex and names ignore alpha)
            var format = currentPreferredFormat;
            if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
                if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
                    format = "rgb";
                }
            }

            var realColor = get({ format: format }),
                displayColor = '';

             //reset background info for preview element
            previewElement.removeClass("sp-clear-display");
            previewElement.css('background-color', 'transparent');

            if (!realColor && allowEmpty) {
                // Update the replaced elements background with icon indicating no color selection
                previewElement.addClass("sp-clear-display");
            }
            else {
                var realHex = realColor.toHexString(),
                    realRgb = realColor.toRgbString();

                // Update the replaced elements background color (with actual selected color)
                if (rgbaSupport || realColor.alpha === 1) {
                    previewElement.css("background-color", realRgb);
                }
                else {
                    previewElement.css("background-color", "transparent");
                    previewElement.css("filter", realColor.toFilter());
                }

                if (opts.showAlpha) {
                    var rgb = realColor.toRgb();
                    rgb.a = 0;
                    var realAlpha = tinycolor(rgb).toRgbString();
                    var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";

                    if (IE) {
                        alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
                    }
                    else {
                        alphaSliderInner.css("background", "-webkit-" + gradient);
                        alphaSliderInner.css("background", "-moz-" + gradient);
                        alphaSliderInner.css("background", "-ms-" + gradient);
                        // Use current syntax gradient on unprefixed property.
                        alphaSliderInner.css("background",
                            "linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
                    }
                }

                displayColor = realColor.toString(format);
            }

            // Update the text entry input as it changes happen
            if (opts.showInput) {
                textInput.val(displayColor);
            }

            if (opts.showPalette) {
                drawPalette();
            }

            drawInitial();
        }

        function updateHelperLocations() {
            var s = currentSaturation;
            var v = currentValue;

            if(allowEmpty && isEmpty) {
                //if selected color is empty, hide the helpers
                alphaSlideHelper.hide();
                slideHelper.hide();
                dragHelper.hide();
            }
            else {
                //make sure helpers are visible
                alphaSlideHelper.show();
                slideHelper.show();
                dragHelper.show();

                // Where to show the little circle in that displays your current selected color
                var dragX = s * dragWidth;
                var dragY = dragHeight - (v * dragHeight);
                dragX = Math.max(
                    -dragHelperHeight,
                    Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
                );
                dragY = Math.max(
                    -dragHelperHeight,
                    Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
                );
                dragHelper.css({
                    "top": dragY + "px",
                    "left": dragX + "px"
                });

                var alphaX = currentAlpha * alphaWidth;
                alphaSlideHelper.css({
                    "left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
                });

                // Where to show the bar that displays your current selected hue
                var slideY = (currentHue) * slideHeight;
                slideHelper.css({
                    "top": (slideY - slideHelperHeight) + "px"
                });
            }
        }

        function updateOriginalInput(fireCallback) {
            var color = get(),
                displayColor = '',
                hasChanged = !tinycolor.equals(color, colorOnShow);

            if (color) {
                displayColor = color.toString(currentPreferredFormat);
                // Update the selection palette with the current color
                addColorToSelectionPalette(color);
            }

            if (isInput) {
                boundElement.val(displayColor);
            }

            if (fireCallback && hasChanged) {
                callbacks.change(color);
                boundElement.trigger('change', [ color ]);
            }
        }

        function reflow() {
            if (!visible) {
                return; // Calculations would be useless and wouldn't be reliable anyways
            }
            dragWidth = dragger.width();
            dragHeight = dragger.height();
            dragHelperHeight = dragHelper.height();
            slideWidth = slider.width();
            slideHeight = slider.height();
            slideHelperHeight = slideHelper.height();
            alphaWidth = alphaSlider.width();
            alphaSlideHelperWidth = alphaSlideHelper.width();

            if (!flat) {
                container.css("position", "absolute");
                if (opts.offset) {
                    container.offset(opts.offset);
                } else {
                    container.offset(getOffset(container, offsetElement));
                }
            }

            updateHelperLocations();

            if (opts.showPalette) {
                drawPalette();
            }

            boundElement.trigger('reflow.spectrum');
        }

        function destroy() {
            boundElement.show();
            offsetElement.unbind("click.spectrum touchstart.spectrum");
            container.remove();
            replacer.remove();
            spectrums[spect.id] = null;
        }

        function option(optionName, optionValue) {
            if (optionName === undefined) {
                return $.extend({}, opts);
            }
            if (optionValue === undefined) {
                return opts[optionName];
            }

            opts[optionName] = optionValue;

            if (optionName === "preferredFormat") {
                currentPreferredFormat = opts.preferredFormat;
            }
            applyOptions();
        }

        function enable() {
            disabled = false;
            boundElement.attr("disabled", false);
            offsetElement.removeClass("sp-disabled");
        }

        function disable() {
            hide();
            disabled = true;
            boundElement.attr("disabled", true);
            offsetElement.addClass("sp-disabled");
        }

        function setOffset(coord) {
            opts.offset = coord;
            reflow();
        }

        initialize();

        var spect = {
            show: show,
            hide: hide,
            toggle: toggle,
            reflow: reflow,
            option: option,
            enable: enable,
            disable: disable,
            offset: setOffset,
            set: function (c) {
                set(c);
                updateOriginalInput();
            },
            get: get,
            destroy: destroy,
            container: container
        };

        spect.id = spectrums.push(spect) - 1;

        return spect;
    }

    /**
    * checkOffset - get the offset below/above and left/right element depending on screen position
    * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
    */
    function getOffset(picker, input) {
        var extraY = 0;
        var dpWidth = picker.outerWidth();
        var dpHeight = picker.outerHeight();
        var inputHeight = input.outerHeight();
        var doc = picker[0].ownerDocument;
        var docElem = doc.documentElement;
        var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
        var viewHeight = docElem.clientHeight + $(doc).scrollTop();
        var offset = input.offset();
        offset.top += inputHeight;

        offset.left -=
            Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
            Math.abs(offset.left + dpWidth - viewWidth) : 0);

        offset.top -=
            Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
            Math.abs(dpHeight + inputHeight - extraY) : extraY));

        return offset;
    }

    /**
    * noop - do nothing
    */
    function noop() {

    }

    /**
    * stopPropagation - makes the code only doing this a little easier to read in line
    */
    function stopPropagation(e) {
        e.stopPropagation();
    }

    /**
    * Create a function bound to a given object
    * Thanks to underscore.js
    */
    function bind(func, obj) {
        var slice = Array.prototype.slice;
        var args = slice.call(arguments, 2);
        return function () {
            return func.apply(obj, args.concat(slice.call(arguments)));
        };
    }

    /**
    * Lightweight drag helper.  Handles containment within the element, so that
    * when dragging, the x is within [0,element.width] and y is within [0,element.height]
    */
    function draggable(element, onmove, onstart, onstop) {
        onmove = onmove || function () { };
        onstart = onstart || function () { };
        onstop = onstop || function () { };
        var doc = document;
        var dragging = false;
        var offset = {};
        var maxHeight = 0;
        var maxWidth = 0;
        var hasTouch = ('ontouchstart' in window);

        var duringDragEvents = {};
        duringDragEvents["selectstart"] = prevent;
        duringDragEvents["dragstart"] = prevent;
        duringDragEvents["touchmove mousemove"] = move;
        duringDragEvents["touchend mouseup"] = stop;

        function prevent(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.returnValue = false;
        }

        function move(e) {
            if (dragging) {
                // Mouseup happened outside of window
                if (IE && doc.documentMode < 9 && !e.button) {
                    return stop();
                }

                var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0];
                var pageX = t0 && t0.pageX || e.pageX;
                var pageY = t0 && t0.pageY || e.pageY;

                var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
                var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));

                if (hasTouch) {
                    // Stop scrolling in iOS
                    prevent(e);
                }

                onmove.apply(element, [dragX, dragY, e]);
            }
        }

        function start(e) {
            var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);

            if (!rightclick && !dragging) {
                if (onstart.apply(element, arguments) !== false) {
                    dragging = true;
                    maxHeight = $(element).height();
                    maxWidth = $(element).width();
                    offset = $(element).offset();

                    $(doc).bind(duringDragEvents);
                    $(doc.body).addClass("sp-dragging");

                    move(e);

                    prevent(e);
                }
            }
        }

        function stop() {
            if (dragging) {
                $(doc).unbind(duringDragEvents);
                $(doc.body).removeClass("sp-dragging");

                // Wait a tick before notifying observers to allow the click event
                // to fire in Chrome.
                setTimeout(function() {
                    onstop.apply(element, arguments);
                }, 0);
            }
            dragging = false;
        }

        $(element).bind("touchstart mousedown", start);
    }

    function throttle(func, wait, debounce) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var throttler = function () {
                timeout = null;
                func.apply(context, args);
            };
            if (debounce) clearTimeout(timeout);
            if (debounce || !timeout) timeout = setTimeout(throttler, wait);
        };
    }

    function inputTypeColorSupport() {
        return $.fn.spectrum.inputTypeColorSupport();
    }

    /**
    * Define a jQuery plugin
    */
    var dataID = "spectrum.id";
    $.fn.spectrum = function (opts, extra) {

        if (typeof opts == "string") {

            var returnValue = this;
            var args = Array.prototype.slice.call( arguments, 1 );

            this.each(function () {
                var spect = spectrums[$(this).data(dataID)];
                if (spect) {
                    var method = spect[opts];
                    if (!method) {
                        throw new Error( "Spectrum: no such method: '" + opts + "'" );
                    }

                    if (opts == "get") {
                        returnValue = spect.get();
                    }
                    else if (opts == "container") {
                        returnValue = spect.container;
                    }
                    else if (opts == "option") {
                        returnValue = spect.option.apply(spect, args);
                    }
                    else if (opts == "destroy") {
                        spect.destroy();
                        $(this).removeData(dataID);
                    }
                    else {
                        method.apply(spect, args);
                    }
                }
            });

            return returnValue;
        }

        // Initializing a new instance of spectrum
        return this.spectrum("destroy").each(function () {
            var options = $.extend({}, opts, $(this).data());
            var spect = spectrum(this, options);
            $(this).data(dataID, spect.id);
        });
    };

    $.fn.spectrum.load = true;
    $.fn.spectrum.loadOpts = {};
    $.fn.spectrum.draggable = draggable;
    $.fn.spectrum.defaults = defaultOpts;
    $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
        if (typeof inputTypeColorSupport._cachedResult === "undefined") {
            var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null
            inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== "";
        }
        return inputTypeColorSupport._cachedResult;
    };

    $.spectrum = { };
    $.spectrum.localization = { };
    $.spectrum.palettes = { };

    $.fn.spectrum.processNativeColorInputs = function () {
        var colorInputs = $("input[type=color]");
        if (colorInputs.length && !inputTypeColorSupport()) {
            colorInputs.spectrum({
                preferredFormat: "hex6"
            });
        }
    };

    // TinyColor v1.1.2
    // https://github.com/bgrins/TinyColor
    // Brian Grinstead, MIT License

    (function() {

    var trimLeft = /^[\s,#]+/,
        trimRight = /\s+$/,
        tinyCounter = 0,
        math = Math,
        mathRound = math.round,
        mathMin = math.min,
        mathMax = math.max,
        mathRandom = math.random;

    var tinycolor = function(color, opts) {

        color = (color) ? color : '';
        opts = opts || { };

        // If input is already a tinycolor, return itself
        if (color instanceof tinycolor) {
           return color;
        }
        // If we are called as a function, call using new instead
        if (!(this instanceof tinycolor)) {
            return new tinycolor(color, opts);
        }

        var rgb = inputToRGB(color);
        this._originalInput = color,
        this._r = rgb.r,
        this._g = rgb.g,
        this._b = rgb.b,
        this._a = rgb.a,
        this._roundA = mathRound(100*this._a) / 100,
        this._format = opts.format || rgb.format;
        this._gradientType = opts.gradientType;

        // Don't let the range of [0,255] come back in [0,1].
        // Potentially lose a little bit of precision here, but will fix issues where
        // .5 gets interpreted as half of the total, instead of half of 1
        // If it was supposed to be 128, this was already taken care of by `inputToRgb`
        if (this._r < 1) { this._r = mathRound(this._r); }
        if (this._g < 1) { this._g = mathRound(this._g); }
        if (this._b < 1) { this._b = mathRound(this._b); }

        this._ok = rgb.ok;
        this._tc_id = tinyCounter++;
    };

    tinycolor.prototype = {
        isDark: function() {
            return this.getBrightness() < 128;
        },
        isLight: function() {
            return !this.isDark();
        },
        isValid: function() {
            return this._ok;
        },
        getOriginalInput: function() {
          return this._originalInput;
        },
        getFormat: function() {
            return this._format;
        },
        getAlpha: function() {
            return this._a;
        },
        getBrightness: function() {
            var rgb = this.toRgb();
            return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
        },
        setAlpha: function(value) {
            this._a = boundAlpha(value);
            this._roundA = mathRound(100*this._a) / 100;
            return this;
        },
        toHsv: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
        },
        toHsvString: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
            return (this._a == 1) ?
              "hsv("  + h + ", " + s + "%, " + v + "%)" :
              "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
        },
        toHsl: function() {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
        },
        toHslString: function() {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
            return (this._a == 1) ?
              "hsl("  + h + ", " + s + "%, " + l + "%)" :
              "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
        },
        toHex: function(allow3Char) {
            return rgbToHex(this._r, this._g, this._b, allow3Char);
        },
        toHexString: function(allow3Char) {
            return '#' + this.toHex(allow3Char);
        },
        toHex8: function() {
            return rgbaToHex(this._r, this._g, this._b, this._a);
        },
        toHex8String: function() {
            return '#' + this.toHex8();
        },
        toRgb: function() {
            return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
        },
        toRgbString: function() {
            return (this._a == 1) ?
              "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
              "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
        },
        toPercentageRgb: function() {
            return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
        },
        toPercentageRgbString: function() {
            return (this._a == 1) ?
              "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
              "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
        },
        toName: function() {
            if (this._a === 0) {
                return "transparent";
            }

            if (this._a < 1) {
                return false;
            }

            return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        },
        toFilter: function(secondColor) {
            var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
            var secondHex8String = hex8String;
            var gradientType = this._gradientType ? "GradientType = 1, " : "";

            if (secondColor) {
                var s = tinycolor(secondColor);
                secondHex8String = s.toHex8String();
            }

            return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
        },
        toString: function(format) {
            var formatSet = !!format;
            format = format || this._format;

            var formattedString = false;
            var hasAlpha = this._a < 1 && this._a >= 0;
            var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");

            if (needsAlphaFormat) {
                // Special case for "transparent", all other non-alpha formats
                // will return rgba when there is transparency.
                if (format === "name" && this._a === 0) {
                    return this.toName();
                }
                return this.toRgbString();
            }
            if (format === "rgb") {
                formattedString = this.toRgbString();
            }
            if (format === "prgb") {
                formattedString = this.toPercentageRgbString();
            }
            if (format === "hex" || format === "hex6") {
                formattedString = this.toHexString();
            }
            if (format === "hex3") {
                formattedString = this.toHexString(true);
            }
            if (format === "hex8") {
                formattedString = this.toHex8String();
            }
            if (format === "name") {
                formattedString = this.toName();
            }
            if (format === "hsl") {
                formattedString = this.toHslString();
            }
            if (format === "hsv") {
                formattedString = this.toHsvString();
            }

            return formattedString || this.toHexString();
        },

        _applyModification: function(fn, args) {
            var color = fn.apply(null, [this].concat([].slice.call(args)));
            this._r = color._r;
            this._g = color._g;
            this._b = color._b;
            this.setAlpha(color._a);
            return this;
        },
        lighten: function() {
            return this._applyModification(lighten, arguments);
        },
        brighten: function() {
            return this._applyModification(brighten, arguments);
        },
        darken: function() {
            return this._applyModification(darken, arguments);
        },
        desaturate: function() {
            return this._applyModification(desaturate, arguments);
        },
        saturate: function() {
            return this._applyModification(saturate, arguments);
        },
        greyscale: function() {
            return this._applyModification(greyscale, arguments);
        },
        spin: function() {
            return this._applyModification(spin, arguments);
        },

        _applyCombination: function(fn, args) {
            return fn.apply(null, [this].concat([].slice.call(args)));
        },
        analogous: function() {
            return this._applyCombination(analogous, arguments);
        },
        complement: function() {
            return this._applyCombination(complement, arguments);
        },
        monochromatic: function() {
            return this._applyCombination(monochromatic, arguments);
        },
        splitcomplement: function() {
            return this._applyCombination(splitcomplement, arguments);
        },
        triad: function() {
            return this._applyCombination(triad, arguments);
        },
        tetrad: function() {
            return this._applyCombination(tetrad, arguments);
        }
    };

    // If input is an object, force 1 into "1.0" to handle ratios properly
    // String input requires "1.0" as input, so 1 will be treated as 1
    tinycolor.fromRatio = function(color, opts) {
        if (typeof color == "object") {
            var newColor = {};
            for (var i in color) {
                if (color.hasOwnProperty(i)) {
                    if (i === "a") {
                        newColor[i] = color[i];
                    }
                    else {
                        newColor[i] = convertToPercentage(color[i]);
                    }
                }
            }
            color = newColor;
        }

        return tinycolor(color, opts);
    };

    // Given a string or object, convert that input to RGB
    // Possible string inputs:
    //
    //     "red"
    //     "#f00" or "f00"
    //     "#ff0000" or "ff0000"
    //     "#ff000000" or "ff000000"
    //     "rgb 255 0 0" or "rgb (255, 0, 0)"
    //     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
    //     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
    //     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
    //     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
    //     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
    //     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
    //
    function inputToRGB(color) {

        var rgb = { r: 0, g: 0, b: 0 };
        var a = 1;
        var ok = false;
        var format = false;

        if (typeof color == "string") {
            color = stringInputToObject(color);
        }

        if (typeof color == "object") {
            if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
                rgb = rgbToRgb(color.r, color.g, color.b);
                ok = true;
                format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
            }
            else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
                color.s = convertToPercentage(color.s);
                color.v = convertToPercentage(color.v);
                rgb = hsvToRgb(color.h, color.s, color.v);
                ok = true;
                format = "hsv";
            }
            else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
                color.s = convertToPercentage(color.s);
                color.l = convertToPercentage(color.l);
                rgb = hslToRgb(color.h, color.s, color.l);
                ok = true;
                format = "hsl";
            }

            if (color.hasOwnProperty("a")) {
                a = color.a;
            }
        }

        a = boundAlpha(a);

        return {
            ok: ok,
            format: color.format || format,
            r: mathMin(255, mathMax(rgb.r, 0)),
            g: mathMin(255, mathMax(rgb.g, 0)),
            b: mathMin(255, mathMax(rgb.b, 0)),
            a: a
        };
    }


    // Conversion Functions
    // --------------------

    // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
    // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

    // `rgbToRgb`
    // Handle bounds / percentage checking to conform to CSS color spec
    // <http://www.w3.org/TR/css3-color/>
    // *Assumes:* r, g, b in [0, 255] or [0, 1]
    // *Returns:* { r, g, b } in [0, 255]
    function rgbToRgb(r, g, b){
        return {
            r: bound01(r, 255) * 255,
            g: bound01(g, 255) * 255,
            b: bound01(b, 255) * 255
        };
    }

    // `rgbToHsl`
    // Converts an RGB color value to HSL.
    // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
    // *Returns:* { h, s, l } in [0,1]
    function rgbToHsl(r, g, b) {

        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);

        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, l = (max + min) / 2;

        if(max == min) {
            h = s = 0; // achromatic
        }
        else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }

            h /= 6;
        }

        return { h: h, s: s, l: l };
    }

    // `hslToRgb`
    // Converts an HSL color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
    function hslToRgb(h, s, l) {
        var r, g, b;

        h = bound01(h, 360);
        s = bound01(s, 100);
        l = bound01(l, 100);

        function hue2rgb(p, q, t) {
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        if(s === 0) {
            r = g = b = l; // achromatic
        }
        else {
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }

        return { r: r * 255, g: g * 255, b: b * 255 };
    }

    // `rgbToHsv`
    // Converts an RGB color value to HSV
    // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
    // *Returns:* { h, s, v } in [0,1]
    function rgbToHsv(r, g, b) {

        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);

        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, v = max;

        var d = max - min;
        s = max === 0 ? 0 : d / max;

        if(max == min) {
            h = 0; // achromatic
        }
        else {
            switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }
        return { h: h, s: s, v: v };
    }

    // `hsvToRgb`
    // Converts an HSV color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
     function hsvToRgb(h, s, v) {

        h = bound01(h, 360) * 6;
        s = bound01(s, 100);
        v = bound01(v, 100);

        var i = math.floor(h),
            f = h - i,
            p = v * (1 - s),
            q = v * (1 - f * s),
            t = v * (1 - (1 - f) * s),
            mod = i % 6,
            r = [v, q, p, p, t, v][mod],
            g = [t, v, v, q, p, p][mod],
            b = [p, p, t, v, v, q][mod];

        return { r: r * 255, g: g * 255, b: b * 255 };
    }

    // `rgbToHex`
    // Converts an RGB color to hex
    // Assumes r, g, and b are contained in the set [0, 255]
    // Returns a 3 or 6 character hex
    function rgbToHex(r, g, b, allow3Char) {

        var hex = [
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16))
        ];

        // Return a 3 character hex if possible
        if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
            return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }

        return hex.join("");
    }
        // `rgbaToHex`
        // Converts an RGBA color plus alpha transparency to hex
        // Assumes r, g, b and a are contained in the set [0, 255]
        // Returns an 8 character hex
        function rgbaToHex(r, g, b, a) {

            var hex = [
                pad2(convertDecimalToHex(a)),
                pad2(mathRound(r).toString(16)),
                pad2(mathRound(g).toString(16)),
                pad2(mathRound(b).toString(16))
            ];

            return hex.join("");
        }

    // `equals`
    // Can be called with any tinycolor input
    tinycolor.equals = function (color1, color2) {
        if (!color1 || !color2) { return false; }
        return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
    };
    tinycolor.random = function() {
        return tinycolor.fromRatio({
            r: mathRandom(),
            g: mathRandom(),
            b: mathRandom()
        });
    };


    // Modification Functions
    // ----------------------
    // Thanks to less.js for some of the basics here
    // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

    function desaturate(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }

    function saturate(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }

    function greyscale(color) {
        return tinycolor(color).desaturate(100);
    }

    function lighten (color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }

    function brighten(color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var rgb = tinycolor(color).toRgb();
        rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
        rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
        rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
        return tinycolor(rgb);
    }

    function darken (color, amount) {
        amount = (amount === 0) ? 0 : (amount || 10);
        var hsl = tinycolor(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }

    // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
    // Values outside of this range will be wrapped into this range.
    function spin(color, amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (mathRound(hsl.h) + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
    }

    // Combination Functions
    // ---------------------
    // Thanks to jQuery xColor for some of the ideas behind these
    // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

    function complement(color) {
        var hsl = tinycolor(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor(hsl);
    }

    function triad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
        ];
    }

    function tetrad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
        ];
    }

    function splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
            tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
        ];
    }

    function analogous(color, results, slices) {
        results = results || 6;
        slices = slices || 30;

        var hsl = tinycolor(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor(color)];

        for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
            hsl.h = (hsl.h + part) % 360;
            ret.push(tinycolor(hsl));
        }
        return ret;
    }

    function monochromatic(color, results) {
        results = results || 6;
        var hsv = tinycolor(color).toHsv();
        var h = hsv.h, s = hsv.s, v = hsv.v;
        var ret = [];
        var modification = 1 / results;

        while (results--) {
            ret.push(tinycolor({ h: h, s: s, v: v}));
            v = (v + modification) % 1;
        }

        return ret;
    }

    // Utility Functions
    // ---------------------

    tinycolor.mix = function(color1, color2, amount) {
        amount = (amount === 0) ? 0 : (amount || 50);

        var rgb1 = tinycolor(color1).toRgb();
        var rgb2 = tinycolor(color2).toRgb();

        var p = amount / 100;
        var w = p * 2 - 1;
        var a = rgb2.a - rgb1.a;

        var w1;

        if (w * a == -1) {
            w1 = w;
        } else {
            w1 = (w + a) / (1 + w * a);
        }

        w1 = (w1 + 1) / 2;

        var w2 = 1 - w1;

        var rgba = {
            r: rgb2.r * w1 + rgb1.r * w2,
            g: rgb2.g * w1 + rgb1.g * w2,
            b: rgb2.b * w1 + rgb1.b * w2,
            a: rgb2.a * p  + rgb1.a * (1 - p)
        };

        return tinycolor(rgba);
    };


    // Readability Functions
    // ---------------------
    // <http://www.w3.org/TR/AERT#color-contrast>

    // `readability`
    // Analyze the 2 colors and returns an object with the following properties:
    //    `brightness`: difference in brightness between the two colors
    //    `color`: difference in color/hue between the two colors
    tinycolor.readability = function(color1, color2) {
        var c1 = tinycolor(color1);
        var c2 = tinycolor(color2);
        var rgb1 = c1.toRgb();
        var rgb2 = c2.toRgb();
        var brightnessA = c1.getBrightness();
        var brightnessB = c2.getBrightness();
        var colorDiff = (
            Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
            Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
            Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
        );

        return {
            brightness: Math.abs(brightnessA - brightnessB),
            color: colorDiff
        };
    };

    // `readable`
    // http://www.w3.org/TR/AERT#color-contrast
    // Ensure that foreground and background color combinations provide sufficient contrast.
    // *Example*
    //    tinycolor.isReadable("#000", "#111") => false
    tinycolor.isReadable = function(color1, color2) {
        var readability = tinycolor.readability(color1, color2);
        return readability.brightness > 125 && readability.color > 500;
    };

    // `mostReadable`
    // Given a base color and a list of possible foreground or background
    // colors for that base, returns the most readable color.
    // *Example*
    //    tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
    tinycolor.mostReadable = function(baseColor, colorList) {
        var bestColor = null;
        var bestScore = 0;
        var bestIsReadable = false;
        for (var i=0; i < colorList.length; i++) {

            // We normalize both around the "acceptable" breaking point,
            // but rank brightness constrast higher than hue.

            var readability = tinycolor.readability(baseColor, colorList[i]);
            var readable = readability.brightness > 125 && readability.color > 500;
            var score = 3 * (readability.brightness / 125) + (readability.color / 500);

            if ((readable && ! bestIsReadable) ||
                (readable && bestIsReadable && score > bestScore) ||
                ((! readable) && (! bestIsReadable) && score > bestScore)) {
                bestIsReadable = readable;
                bestScore = score;
                bestColor = tinycolor(colorList[i]);
            }
        }
        return bestColor;
    };


    // Big List of Colors
    // ------------------
    // <http://www.w3.org/TR/css3-color/#svg-color>
    var names = tinycolor.names = {
        aliceblue: "f0f8ff",
        antiquewhite: "faebd7",
        aqua: "0ff",
        aquamarine: "7fffd4",
        azure: "f0ffff",
        beige: "f5f5dc",
        bisque: "ffe4c4",
        black: "000",
        blanchedalmond: "ffebcd",
        blue: "00f",
        blueviolet: "8a2be2",
        brown: "a52a2a",
        burlywood: "deb887",
        burntsienna: "ea7e5d",
        cadetblue: "5f9ea0",
        chartreuse: "7fff00",
        chocolate: "d2691e",
        coral: "ff7f50",
        cornflowerblue: "6495ed",
        cornsilk: "fff8dc",
        crimson: "dc143c",
        cyan: "0ff",
        darkblue: "00008b",
        darkcyan: "008b8b",
        darkgoldenrod: "b8860b",
        darkgray: "a9a9a9",
        darkgreen: "006400",
        darkgrey: "a9a9a9",
        darkkhaki: "bdb76b",
        darkmagenta: "8b008b",
        darkolivegreen: "556b2f",
        darkorange: "ff8c00",
        darkorchid: "9932cc",
        darkred: "8b0000",
        darksalmon: "e9967a",
        darkseagreen: "8fbc8f",
        darkslateblue: "483d8b",
        darkslategray: "2f4f4f",
        darkslategrey: "2f4f4f",
        darkturquoise: "00ced1",
        darkviolet: "9400d3",
        deeppink: "ff1493",
        deepskyblue: "00bfff",
        dimgray: "696969",
        dimgrey: "696969",
        dodgerblue: "1e90ff",
        firebrick: "b22222",
        floralwhite: "fffaf0",
        forestgreen: "228b22",
        fuchsia: "f0f",
        gainsboro: "dcdcdc",
        ghostwhite: "f8f8ff",
        gold: "ffd700",
        goldenrod: "daa520",
        gray: "808080",
        green: "008000",
        greenyellow: "adff2f",
        grey: "808080",
        honeydew: "f0fff0",
        hotpink: "ff69b4",
        indianred: "cd5c5c",
        indigo: "4b0082",
        ivory: "fffff0",
        khaki: "f0e68c",
        lavender: "e6e6fa",
        lavenderblush: "fff0f5",
        lawngreen: "7cfc00",
        lemonchiffon: "fffacd",
        lightblue: "add8e6",
        lightcoral: "f08080",
        lightcyan: "e0ffff",
        lightgoldenrodyellow: "fafad2",
        lightgray: "d3d3d3",
        lightgreen: "90ee90",
        lightgrey: "d3d3d3",
        lightpink: "ffb6c1",
        lightsalmon: "ffa07a",
        lightseagreen: "20b2aa",
        lightskyblue: "87cefa",
        lightslategray: "789",
        lightslategrey: "789",
        lightsteelblue: "b0c4de",
        lightyellow: "ffffe0",
        lime: "0f0",
        limegreen: "32cd32",
        linen: "faf0e6",
        magenta: "f0f",
        maroon: "800000",
        mediumaquamarine: "66cdaa",
        mediumblue: "0000cd",
        mediumorchid: "ba55d3",
        mediumpurple: "9370db",
        mediumseagreen: "3cb371",
        mediumslateblue: "7b68ee",
        mediumspringgreen: "00fa9a",
        mediumturquoise: "48d1cc",
        mediumvioletred: "c71585",
        midnightblue: "191970",
        mintcream: "f5fffa",
        mistyrose: "ffe4e1",
        moccasin: "ffe4b5",
        navajowhite: "ffdead",
        navy: "000080",
        oldlace: "fdf5e6",
        olive: "808000",
        olivedrab: "6b8e23",
        orange: "ffa500",
        orangered: "ff4500",
        orchid: "da70d6",
        palegoldenrod: "eee8aa",
        palegreen: "98fb98",
        paleturquoise: "afeeee",
        palevioletred: "db7093",
        papayawhip: "ffefd5",
        peachpuff: "ffdab9",
        peru: "cd853f",
        pink: "ffc0cb",
        plum: "dda0dd",
        powderblue: "b0e0e6",
        purple: "800080",
        rebeccapurple: "663399",
        red: "f00",
        rosybrown: "bc8f8f",
        royalblue: "4169e1",
        saddlebrown: "8b4513",
        salmon: "fa8072",
        sandybrown: "f4a460",
        seagreen: "2e8b57",
        seashell: "fff5ee",
        sienna: "a0522d",
        silver: "c0c0c0",
        skyblue: "87ceeb",
        slateblue: "6a5acd",
        slategray: "708090",
        slategrey: "708090",
        snow: "fffafa",
        springgreen: "00ff7f",
        steelblue: "4682b4",
        tan: "d2b48c",
        teal: "008080",
        thistle: "d8bfd8",
        tomato: "ff6347",
        turquoise: "40e0d0",
        violet: "ee82ee",
        wheat: "f5deb3",
        white: "fff",
        whitesmoke: "f5f5f5",
        yellow: "ff0",
        yellowgreen: "9acd32"
    };

    // Make it easy to access colors via `hexNames[hex]`
    var hexNames = tinycolor.hexNames = flip(names);


    // Utilities
    // ---------

    // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
    function flip(o) {
        var flipped = { };
        for (var i in o) {
            if (o.hasOwnProperty(i)) {
                flipped[o[i]] = i;
            }
        }
        return flipped;
    }

    // Return a valid alpha value [0,1] with all invalid values being set to 1
    function boundAlpha(a) {
        a = parseFloat(a);

        if (isNaN(a) || a < 0 || a > 1) {
            a = 1;
        }

        return a;
    }

    // Take input from [0, n] and return it as [0, 1]
    function bound01(n, max) {
        if (isOnePointZero(n)) { n = "100%"; }

        var processPercent = isPercentage(n);
        n = mathMin(max, mathMax(0, parseFloat(n)));

        // Automatically convert percentage into number
        if (processPercent) {
            n = parseInt(n * max, 10) / 100;
        }

        // Handle floating point rounding errors
        if ((math.abs(n - max) < 0.000001)) {
            return 1;
        }

        // Convert into [0, 1] range if it isn't already
        return (n % max) / parseFloat(max);
    }

    // Force a number between 0 and 1
    function clamp01(val) {
        return mathMin(1, mathMax(0, val));
    }

    // Parse a base-16 hex value into a base-10 integer
    function parseIntFromHex(val) {
        return parseInt(val, 16);
    }

    // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
    // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
    function isOnePointZero(n) {
        return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
    }

    // Check to see if string passed in is a percentage
    function isPercentage(n) {
        return typeof n === "string" && n.indexOf('%') != -1;
    }

    // Force a hex value to have 2 characters
    function pad2(c) {
        return c.length == 1 ? '0' + c : '' + c;
    }

    // Replace a decimal with it's percentage value
    function convertToPercentage(n) {
        if (n <= 1) {
            n = (n * 100) + "%";
        }

        return n;
    }

    // Converts a decimal to a hex value
    function convertDecimalToHex(d) {
        return Math.round(parseFloat(d) * 255).toString(16);
    }
    // Converts a hex value to a decimal
    function convertHexToDecimal(h) {
        return (parseIntFromHex(h) / 255);
    }

    var matchers = (function() {

        // <http://www.w3.org/TR/css3-values/#integers>
        var CSS_INTEGER = "[-\\+]?\\d+%?";

        // <http://www.w3.org/TR/css3-values/#number-value>
        var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

        // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
        var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

        // Actual matching.
        // Parentheses and commas are optional, but not required.
        // Whitespace can take the place of commas or opening paren
        var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

        return {
            rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
            rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
            hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
            hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
            hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
            hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
            hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
            hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
            hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
        };
    })();

    // `stringInputToObject`
    // Permissive string parsing.  Take in a number of formats, and output an object
    // based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
    function stringInputToObject(color) {

        color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
        var named = false;
        if (names[color]) {
            color = names[color];
            named = true;
        }
        else if (color == 'transparent') {
            return { r: 0, g: 0, b: 0, a: 0, format: "name" };
        }

        // Try to match string input using regular expressions.
        // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
        // Just return an object and let the conversion functions handle that.
        // This way the result will be the same whether the tinycolor is initialized with string or object.
        var match;
        if ((match = matchers.rgb.exec(color))) {
            return { r: match[1], g: match[2], b: match[3] };
        }
        if ((match = matchers.rgba.exec(color))) {
            return { r: match[1], g: match[2], b: match[3], a: match[4] };
        }
        if ((match = matchers.hsl.exec(color))) {
            return { h: match[1], s: match[2], l: match[3] };
        }
        if ((match = matchers.hsla.exec(color))) {
            return { h: match[1], s: match[2], l: match[3], a: match[4] };
        }
        if ((match = matchers.hsv.exec(color))) {
            return { h: match[1], s: match[2], v: match[3] };
        }
        if ((match = matchers.hsva.exec(color))) {
            return { h: match[1], s: match[2], v: match[3], a: match[4] };
        }
        if ((match = matchers.hex8.exec(color))) {
            return {
                a: convertHexToDecimal(match[1]),
                r: parseIntFromHex(match[2]),
                g: parseIntFromHex(match[3]),
                b: parseIntFromHex(match[4]),
                format: named ? "name" : "hex8"
            };
        }
        if ((match = matchers.hex6.exec(color))) {
            return {
                r: parseIntFromHex(match[1]),
                g: parseIntFromHex(match[2]),
                b: parseIntFromHex(match[3]),
                format: named ? "name" : "hex"
            };
        }
        if ((match = matchers.hex3.exec(color))) {
            return {
                r: parseIntFromHex(match[1] + '' + match[1]),
                g: parseIntFromHex(match[2] + '' + match[2]),
                b: parseIntFromHex(match[3] + '' + match[3]),
                format: named ? "name" : "hex"
            };
        }

        return false;
    }

    window.tinycolor = tinycolor;
    })();

    $(function () {
        if ($.fn.spectrum.load) {
            $.fn.spectrum.processNativeColorInputs();
        }
    });

})(jQuery);

define("../lib/spectrum", function(){});

/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

var GLOBAL = GLOBAL || {};
GLOBAL.user = {
    area: "sh"
};
GLOBAL.currentDate = Com.date.getCurrentDate();



define(
    '../ancestor/Ancestor',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };


    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Album.Crop.js
 * @path:   js-src/album/
 * @desc:   截图用插件
 * @author: gengwei@qiyi.com
 * @date:   2013-05-10
 */
define(
    '../ancestor/Ancestor.Crop',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        (function($, undefined) {
            $.widget('ui.imageCrop', {
                options: {
                    'gallery': null,
                    'cropimg': null,
                    'results': null
                },
                $container: null,
                _jCorpObj: null,
                _scaleInUse: null,
                _create: function(options) {
                    this.options = $.extend({}, this.options, options);
                    this.$container = this.element;
                    this._bindEvents(options);
                    this.$container.data('imageCrop', this);
                },
                enable: function() {
                    this.$container.find('input, button').attr('disabled', false);
                    this.$container.find('div.operation').removeClass('disabled');
                },
                disable: function() {
                    this.$container.find('input, button').attr('disabled', true);
                    this.$container.find('div.operation').addClass('disabled');
                },
                getValue: function() {
                    var $results = this.$container.find(this.options.results);
                    var data = {};
                    $results.find('button').each(function(index, element) {
                        var $button = $(this);
                        var width = $button.data('width');
                        var height = $button.data('height');
                        var imgsrc = $button.data('imgsrc');
                        var coord = $button.data('coord');
                        if (imgsrc && coord) {
                            data[width + '-' + height] = {
                                index: index,
                                imgsrc: imgsrc,
                                spath: $button.data('spath'),
                                w: width,
                                h: height,
                                x1: Math.floor(coord.x),
                                y1: Math.floor(coord.y),
                                x2: Math.floor(coord.x2),
                                y2: Math.floor(coord.y2),
                                data: $button.data('data') || {}
                            };
                        }
                    });
                    return data;
                },
                setValue: function(value) {
                    var that = this;
                    var $results = this.$container.find(this.options.results);
                    var $gallery = this.$container.find(this.options.gallery);
                    var findImage = function(imgsrc) {
                        var $image = null;
                        $gallery.find('img').each(function(index, element) {
                            if (imgsrc == $(this).attr('src')) {
                                $image = $(this);
                            }
                        });
                        return $image;
                    };
                    $results.find('button').each(function(index, element) {
                        var $button = $(this);
                        var width = $button.data('width');
                        var height = $button.data('height');
                        var data = value[width + '-' + height];
                        var coord, imgsrc, $image;
                        if (!data && !$image) {
                            return;
                        }
                        imgsrc = data.imgsrc;
                        $image = findImage(imgsrc);
                        coord = {
                            x: data.x1,
                            y: data.y1,
                            x2: data.x2,
                            y2: data.y2,
                            w: data.x2 - data.x1,
                            h: data.y2 - data.y1
                        };
                        $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                        $button.data('imgsrc', imgsrc);
                        $button.data('coord', coord);
                        $button.data('spath', data.spath);
                        $button.data('data', data.data);
                        if ($image) {
                            that._updateCoord.call(that, coord, $button, $image.data('width'), $image.data('height'));
                        }
                    });
                },
                addImages: function(images, callback) {
                    var $gallery = this.$container.find(this.options.gallery);
                    var gallery = this.$container.find('.slideshow').data('gallery');
                    var oldTotal;
                    var total = images.length;
                    var afterImageLoad = function() {
                        total--;
                        if (0 === total) {
                            if (callback) {
                                callback();
                            }
                        }
                    };
                    $.each(images, function(index, image) {
                        var $imgdiv, data;
                        data = {
                            imgsrc: image.url
                        };
                        if (image.shot) {
                            // 视频截图
                            data.type = 1;
                            data.area = image.area;
                        } else {
                            // 数据回填    
                            data.spath = image.spath;
                            data.type = 0;
                            data.data = image.data;
                        }
                        $imgdiv = $('<img src="' + data.imgsrc + '">');
                        $imgdiv.data(data).load(function(e) {
                            Com.Image.procThumbnail($(this), 128, 80);
                            afterImageLoad();
                        }).error(function(e) {
                            afterImageLoad();
                        });
                        $gallery.append($('<li style="position:relative" class="item" />').append($imgdiv));
                    });
                    oldTotal = gallery.totalItems;
                    gallery.update();
                    gallery.scrollTo(oldTotal);
                },
                // 计算初始截图位置
                _calcInitCoord: function(origWidth, origHeight, scaleWidth, scaleHeight) {
                    var left, top;
                    var newWidth = origWidth * 2 / 3;
                    var newHeight = newWidth * scaleHeight / scaleWidth;
                    if (newHeight > origHeight) {
                        newHeight = origHeight;
                        newWidth = newHeight * scaleWidth / scaleHeight;
                    }
                    newWidth = Math.floor(newWidth);
                    newHeight = Math.floor(newHeight);
                    left = Math.floor((origWidth - newWidth) / 2);
                    top = Math.floor((origHeight - newHeight) / 2);
                    return {
                        x: left,
                        y: top,
                        x2: left + newWidth,
                        y2: top + newHeight
                    };
                },
                // 选择一个比例
                _selectScale: function($button) {
                    var imgsrc = $button.data('imgsrc');
                    var coord = $button.data('coord');
                    $button.data('inuse', true);
                    this._scaleInUse = {
                        width: $button.data('width'),
                        height: $button.data('height'),
                        button: $button,
                        imgsrc: imgsrc,
                        coord: coord
                    };
                    if (imgsrc && coord) {
                        // if is already cropped...
                        this._selectOrigImg(imgsrc);
                    } else {
                        this._selectOrigImg(imgsrc);
                    }
                },
                // 选择一个原始图
                _selectOrigImg: function(imgsrc) {
                    var $gallery = this.$container.find(this.options.gallery);
                    var $cropimg = this.$container.find(this.options.cropimg);
                    $image = $gallery.find('img').filter(function(index, element) {
                        return $(this).attr('src') == imgsrc;
                    });
                    if ($image.length > 0) {
                        $image.click();
                    } else if (1 == $gallery.find('img').length) {
                        $gallery.find('img').eq(0).click();
                    } else {
                        $gallery.find('li').removeClass('active');
                        $cropimg.empty();
                    }
                },
                // 设置 jCorp 对象
                _setupJCorp: function($image, updateCoords, scaleInUse, coord) {
                    var that = this;
                    this._jCorpObj && this._jCorpObj.destroy();
                    this._jCorpObj = null;
                    $image.Jcrop({
                        keySupport: false,
                        onSelect: updateCoords,
                        onChange: updateCoords,
                        aspectRatio: scaleInUse.width / scaleInUse.height,
                        trueSize: [$image.data('width'), $image.data('height')]
                    }, function() {
                        that._jCorpObj = this;
                        that._jCorpObj.animateTo([coord.x, coord.y, coord.x2, coord.y2]);
                    });
                },
                // 绑定事件
                _bindEvents: function() {
                    var that = this;
                    var $gallery = this.$container.find(this.options.gallery);
                    var $cropimg = this.$container.find(this.options.cropimg);
                    var $results = this.$container.find(this.options.results);
                    var $confirm = this.$container.find(this.options.confirm);
                    // 选择裁剪比例
                    $results.delegate('a', 'click', function(e) {
                        e.preventDefault();
                    });
                    $results.delegate('button', 'click', function(e) {
                        var $button = $(this);
                        $button.siblings().removeClass('active');
                        $button.addClass('active');
                        that._selectScale($(this));
                    });
                    // 缩略图的点击事件

                    $gallery.delegate('img', 'click', function(e) {
                        var $thumbimg = $(this),
                            $imgToCrop, $button;
                        var t, scaleWidth, scaleHeight, imageWidth, imageHeight, cropWidth, cropHeight;
                        var imgsrc = $thumbimg.attr('src'),
                            coord;
                        var scaleInUse = that._scaleInUse;
                        // test if is possible to do this action
                        if ($thumbimg.parents('div.operation').hasClass('disabled')) {
                            return;
                        }
                        if (null === scaleInUse) {
                            alert('请先选择缩略图的比例');
                            return false;
                        }
                        if (true === $thumbimg.data('loading')) {
                            alert('该图片现在暂时不可用，请等待上传完成');
                            return false;
                        }
                        // get current scale button
                        $button = scaleInUse.button;
                        imageWidth = $thumbimg.data('width');
                        imageHeight = $thumbimg.data('height');
                        coord = $button.data('coord');
                        // add style to selected image
                        $gallery.find('li').removeClass('active');
                        $thumbimg.parent().addClass('active');
                        // set corp area style and set image to crop area
                        cropWidth = $cropimg.outerWidth() - 2;
                        cropHeight = $cropimg.outerHeight() - 2;
                        t = Com.Image.resizeInside($thumbimg, cropWidth, cropHeight);
                        $imgToCrop = $('<img src="' + imgsrc + '" width="' + t.width + '" height="' + t.height + '">');
                        $imgToCrop.data('width', imageWidth).data('height', imageHeight).data('spath', $thumbimg.data('spath'));
                        $cropimg.css({
                            width: t.width,
                            height: t.height,
                            padding: t.top + 'px ' + (cropWidth - t.width - t.left) + 'px ' + (cropHeight - t.height - t.top) + 'px ' + t.left + 'px'
                        });
                        $cropimg.empty().append($imgToCrop);
                        //
                        if (scaleInUse.imgsrc != imgsrc) {
                            coord = that._calcInitCoord(imageWidth, imageHeight, scaleInUse.width, scaleInUse.height);
                        }
                        // set JCrop
                        $button.data('imgsrc', imgsrc);
                        $button.data('spath', $thumbimg.data('spath') || null);
                        $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                        that._setupJCorp($imgToCrop, function(coord) {
                            that._updateCoord.call(that, coord, $button, imageWidth, imageHeight, true);
                        }, scaleInUse, coord);
                    });


                },
                _updateCoord: function(coord, $button, imageWidth, imageHeight, flush) {
                    var scale = coord.h / $button.find('.preview').height();
                    var newWidth = Math.floor(imageWidth / scale);
                    var newHeight = Math.floor(imageHeight / scale);
                    var left = Math.floor(coord.x / scale);
                    var top = Math.floor(coord.y / scale);
                    if (flush) {
                        $button.data('data', null);
                    }
                    $button.data('coord', coord);
                    $button.find('.preview img').css({
                        width: newWidth,
                        height: newHeight,
                        marginTop: 0 - top,
                        marginLeft: 0 - left
                    });
                }
            });
            $.extend($.ui.imageCrop, {
                uuid: 0,
                _isShow: false
            });
        }(jQuery));

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    Ancestor.Config = (function() {
        var REQUEST_FAIL = "接口响应超时,请稍后再试！";
        var QICHUAN = {

            //image_requestURL: 'http://upload.iqiyi.com/request_image_upload',
            image_requestURL_test: 'http://upload.iqiyi.com/request_image_upload',

            image_uploadURL: 'http://upload.iqiyi.com/image_upload',
            image_uploadURL_inner: 'http://upload.qiyi.domain/image_upload',
            image_uploadURL_test: 'http://upload.iqiyi.com/image_upload',

            deviceId: 'LEGO-uploader',
        };

        var EPG_AUTH = {

            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥

        };

        var CONFIGS_API = {
            url: '/api/configs'
        };

        // 直转点 频道名称
        var CATEGORY_NAME = [];

        // 直播类型
        var LIVE_TYPE = [];

        // 频道分类
        var CHANNEL_TYPE = [];


        // 日志分类
        var LOG_TYPE = [];

        // 备播库标色提示
        var APC_WARNING = {
            NORMAL: 'black',
            RED: 'red',
            ORANGE: '#ffa800'
        };

        var PLATFORM_TYPE = null;
        var PLATFORM_REFER = null;

        // 奇谱url
        var QIPU_URL = (function() {
            var qipuUrl = auth.dev() ? 'http://qipu-test.qiyi.domain/int/entity/nocache/${QIPUID}.json' : 'http://qipu.qiyi.domain/int/entity/nocache/${QIPUID}.json';
            return qipuUrl;
        })();

        return {
            EPG_AUTH: EPG_AUTH,
            LIVE_TYPE: LIVE_TYPE,
            CHANNEL_TYPE: CHANNEL_TYPE,
            QICHUAN: QICHUAN,
            CONFIGS_API: CONFIGS_API,
            LOG_TYPE: LOG_TYPE,
            APC_WARNING: APC_WARNING,
            PLATFORM_REFER: PLATFORM_REFER,
            PLATFORM_TYPE: PLATFORM_TYPE,
            QIPU_URL: QIPU_URL,
            REQUEST_FAIL: REQUEST_FAIL,
            CATEGORY_NAME:CATEGORY_NAME
        };


    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Util',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Util = (function() {

        Date.prototype.format = function (format) {
        var o = {
                  "M+" : this.getMonth() + 1, //month
                  "d+" : this.getDate(), //day
                  "h+" : this.getHours(), //hour
                  "m+" : this.getMinutes(), //minute
                  "s+" : this.getSeconds(), //second
                  "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
                  "S" : this.getMilliseconds() //millisecond
              }

              if (/(y+)/.test(format)) {
                  format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              }

              for (var k in o) {
                  if (new RegExp("(" + k + ")").test(format)) {
                      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                  }
              }
              return format;
          };

        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        /**
         * 设置截图编辑的整体，包括截图、幻灯片、上传三个部分
         * @param $imgcrop Object 整体的DOM结构，jQuery Object
         * @param images Array<String> 初始化用的图片URL数组
         * @param width 如果有幻灯片的话，幻灯片部分的宽度
         */
        var imageCrop = function($imgcrop) {
            // try{
            var $slideshow = $imgcrop.find('.slideshow');
            var $enableBtn = $imgcrop.find('button.button-enable');
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $btnOnline = $imgcrop.find('button.button-online');
            var gallery, t, flag;
            // 设置下面的缩略图
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            gallery = $slideshow.data('gallery');
            t = gallery.totalItems;
            // 设置上传图片按钮
            if ($uploadBtn.length) {
                $uploadBtn.uploadDialog({
                    gallery: $imgcrop.find('.gallery'),
                    onStart: function() {
                        gallery.update();
                        gallery.scrollTo(t);
                    }
                });
            }
            $(window).resize(function(e) {
                gallery.update();
            });
            // 设置截图控件
            $imgcrop.imageCrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            // 设置激活按钮
            if ($('#_entityId').val()) {
                $enableBtn.click(function(e) {
                    $imgcrop.data('imageCrop').enable();
                    $enableBtn.attr('disabled', true);
                    gallery.scrollTo(0);
                });
                $imgcrop.data('imageCrop').disable();
                $enableBtn.attr('disabled', false);
            } else {
                $imgcrop.data('imageCrop').enable();
                $enableBtn.attr('disabled', true);
                $enableBtn.hide();
            }
          $imgcrop.find('.header input').enable();
            if ('1' === $('#ThriftVideoMakeStatus').val() && '1' != $('#entityType').val()) {
                $btnOnline.show();
            } else {
                $btnOnline.hide();
            }
            // 设置在线视频截图
            /*
            if ($btnOnline.length) {
                $('#AlbumEditVideoShot').videoShot({
                    onFinish: function(area, images) {
                        var data = [];
                        $.each(images, function(index, image) {
                            data.push({
                                shot: true,
                                url: image,
                                area: area
                            });
                        });
                        $imgcrop.data('imageCrop').addImages(data);
                    }
                });
                $btnOnline.click(function(e) {
                    $('#AlbumEditVideoShot').dialog('open');
                });
            }
            */

            // }catch(e){}
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            }).trigger('keyup');
            $des.keyup();
        };

        getParam = function($obj) {

            var $container = $obj;
            var params = {};
            var $form = $obj;

            var $elements = $.makeArray($form.prop('elements')).filter(function() {
                return true; //this.name; 
            });

            var name;
            var key;
            $.each($elements, function() {
                name = this.name;
                if (name) {

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $.trim($(this).val()) || '';

                }

            });

            params['logoUrl'] = imageObject($obj);
            return params;

        };

        imageObjectEcho = function($form, value) {

            if (value) {
                value = ('object' == typeof(value) ? value : JSON.parse(value || '[]'));
            } else {
                value = null;
            }
            if (!value) {
                return;
            }

            var imageObject = value;
            var filterType = function(type) {
                var imageData = null;
                $.each(imageObject, function(index, value) {
                    if (value.useType == type) {
                        imageData = value;
                    }
                });
                return imageData;
            };
            var spathToURL = function(images, spath) {
                var url = null;
                $.each(images, function(index, image) {
                    if (spath === image.spath) {
                        url = image.url;
                    }
                });
                return url;
            };

            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var imageCrop = $croparea.data('imageCrop');
                var useType = 699; //parseInt($croparea.find('input[name="useType"]').val(), 10);
                var imageData = filterType(useType);
                var imageRank = imageData && imageData.contentRank ? imageData.contentRank : 0;
                var images = [],
                    results = {};

                if (!imageData) {
                    return;
                }

                // 回显图片分级的选项
                $croparea.find('input[name^="contentRank"]').each(function(key, value) {
                    value.checked = (imageRank == value.value);
                });

                $.each(imageData.materials, function(index, material) {
                    //images.push(material.bigThumbUrl || material.location);
                    // todo: type
                    images.push({
                        spath: material.location,
                        url: material.url,
                        data: material
                    });
                });
                $.each(imageData.images, function(index, image) {
                    var scale = image.editInfo.scale;
                    var cutPosition = image.editInfo.cutPosition.split(',');
                    var width = scale.substring(0, scale.indexOf(':'));
                    var height = scale.substring(scale.indexOf(':') + 1);
                    results[width + '-' + height] = {
                        spath: image.materialLocation,
                        imgsrc: spathToURL(images, image.materialLocation),
                        w: width,
                        h: height,
                        x1: parseInt(cutPosition[0], 10),
                        y1: parseInt(cutPosition[1], 10),
                        x2: parseInt(cutPosition[0], 10) + parseInt(cutPosition[3], 10),
                        y2: parseInt(cutPosition[1], 10) + parseInt(cutPosition[2], 10),
                        data: image
                    };
                });
                imageCrop.addImages(images, function() {
                    imageCrop.setValue(results);
                });
            });
        };


        imageObject = function($form) {
            var imageObject = [];
            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var useType = parseInt($croparea.find('input[name="useType"]').val(), 10);
                var contentRank = parseInt($croparea.find('input[name^="contentRank"]:checked').val(), 10) || 0; // 默认图片分级是无分级，0
                var testFlag = 0;
                var imageData = {
                    materials: [],
                    images: [],
                    useType: 699, //useType,
                    contentRank: contentRank // 图片分级的需求，默认是无分级
                };
                $croparea.find('.gallery img').each(function(index, material) {
                    var $material = $(material);
                    if (true === $material.data('loading')) {
                        return;
                    }
                    var tmp = $material.data('data') || {
                        // @todo
                        'location': $material.data('spath') || '',
                        'url': $material.attr('src'),
                        'fromType': $material.data('type'),
                        'area': 'bj', //$material.data('area'),
                        'width': $material.data('width'),
                        'height': $material.data('height')
                    };
                    imageData.materials.push(tmp);
                    testFlag++;
                });
                $.each($croparea.data('imageCrop').getValue(), function(index, value) {
                    var tmp = $.extend(value.data, {
                        materialLocation: value.spath || value.imgsrc || '',
                        editInfo: {
                            cutPosition: [value.x1, value.y1, value.y2 - value.y1, value.x2 - value.x1].join(','),
                            scale: value.w + ':' + value.h
                        }
                    });
                    imageData.images.push(tmp);
                    //testFlag |= Math.pow(2, value.index);
                });
                var type = $form.find('input[name="entityType"]').val();
                if (('0' == type && (parseInt($form.find('input[name="video.id"]').val(), 10) > 0))
                    // 如果是节目且专辑id禁用表示编目修改
                    || ('1' === type && (parseInt($form.find('input[name="album.id"]').val(), 10) > 0))
                    // 如果是专辑有#_entityId表示修改
                    || ($form.find('input[name=pilosityType]').val() && $form.find('input[name=baseId]').val())
                    // 如果是一文多发有pilosity且有baseId表示修改
                ) {
                    // 节目，专辑, 一文多发，兼容旧的，修改的时候不验证截图
                    testFlag = 99;
                }
                $croparea.find('input[name="_image_crop_' + useType + '"]').val(testFlag);
                imageObject.push(imageData);
            });
            return JSON.stringify(imageObject);
        };


        getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        fillFieldNameWhenChangeSelect = function($form, elClazzName, fieldClazzName) {
            $form.find('.' + elClazzName).on('change', function() {
                var value = $(this).val();
                var $input = $(this).closest('.control-group').find('.' + fieldClazzName);
                $input.attr('name', value);
            });
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };

        var getUploadFiles = function(options, isNew) {
            if (isNew && isNew === true) {
                return new Ancestor.Upload(options);
            }
            if (!uploadFiles) {
                uploadFiles = new Ancestor.Upload(options);
            } else {
                uploadFiles.update(options);
            }
            return uploadFiles;
        };

        var isNormal = function(user) {

            return true;
        };



        // 打开对话框
        var openDlg = function(obj, title, width, height) {

            height = height || 'auto';
            var $container = obj;

            $container.dialog({
                title: title,
                appendTo: null,
                modal: true,
                width: width,
                height: height,
                position: ['top', 'top+20'],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                },
                close: function() {

                }
            });
        };

        var highlight = function(data, key, term) {
            data.forEach(function(item, i) {
                key = key || 'label';
                var label = item[key];
                if (!label || !term) {
                    return;
                }
                item[key] = (item[key] + '').replace(new RegExp('(' + term + ')', 'i'), '<b>$1</b>');
                // 高亮未输入部分
                // if (label.toLowerCase().indexOf(term.toLowerCase()) == 0) {
                //     item[key] = item[key].substr(0, term.length)
                //                   + '<b>'
                //                   + item[key].substr(term.length) + '</b>';
                // }
            });
        };

        var updateParamsBySettings = function(params, entity) {
            if (!params) {
                params = {};
            }

            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Ancestor.Config.PLATFORM_TYPE;
            $.each(platformTypeResponse, function(i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Ancestor.Config.PLATFORM_REFER;
            $.each(platformReferResponse, function(i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params));

            return params;
        };

        var createSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    var fetchData = function() {
                        Ancestor.Dao.getSuggestData(url, param, function(json) {
                            var ret = dataProcess.call(self, json, term);

                            var runNext = function(ret) {
                                if ($.isArray(options.sortBy)) {
                                    sortBy.apply(self, [ret].concat(options.sortBy));
                                } else if ($.isFunction(options.onSortBy)) {
                                    options.onSortBy.apply(self, [ret, term]);
                                }

                                if (options.highlight) {
                                    if ($.isFunction(options.onHighlight)) {
                                        options.onHighlight.apply(self, [ret, term]);
                                    } else {
                                        highlight(ret, null, term);
                                    }
                                }
                                result = ret;
                                if ($.isFunction(options.onLoad)) {
                                    options.onLoad.apply(self, [result, term]);
                                }
                                response(result);
                            };

                            if (options.needFetchMore) {
                                options.fetchMore(ret, runNext);
                            } else {
                                runNext(ret);
                            }
                        });
                    };

                    if (options.needPreProcess) {
                        var channelId = Com.url.getParameter("id");
                        Ancestor.Dao.platSettings({
                            channelId: channelId
                        }, function(json) {
                            if (json.code === 'A00000') {
                                param = updateParamsBySettings(param, json.data);
                                fetchData();
                            }
                        });
                    } else {
                        fetchData();
                    }


                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {


                //////////////////suggest选择后回显设置/////////////////////
                //  ui.item.value=ui.item.name;


                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        };

        var qitan = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width80">${resourceId}</span>' +
                '<span class="contract-width250">{{html name}}</span>' +
                '<span class="contract-width80">${addDate}</span>' +
                '</div></div>';

            var title = {
                resourceId: '评论ID',
                name: '评论名称',
                addDate: '创建时间'
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                url: 'http://api.t.iqiyi.com/qx_api/resource/get_id_by_name',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                otherParam: $.extend({
                    'page_size': 10,
                    'resource_type': $(el).data('type') || 1
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'name': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data.ids;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                label: item.name,
                                value: item.resourceId,
                                id: item.resourceId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };


        var universalCodeCreateSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }
                    Ancestor.Dao.getuniversalCodeData(url, param, function(json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {
                ui.item.value = ui.item.code;
                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        }

        var universalCode = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width250">${code}</span>' +
                '<span style="border-right:none;">${name}</span>' +
                '</div></div>';

            var title = {
                code: '直播频道首拼音',
                name: '直播频道名称',
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            universalCodeCreateSuggest(el, $.extend(true, {

                url: '/api/channel/codelist',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'key': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.name,
                                code: item.code,
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };



        var qitanSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                qitan($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.id);
                        //console.log( $input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };

        var universalCodeSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                universalCode($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.code);
                        //console.log($input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };



        var alternatePlayCollection = function(el, options) {

            var tpl = '<div class="contract-item">' +
                '<span class="contract-width100" style="color:${needAlert}">${qipuId}</span>' +
                '<span class="contract-width150" style="color:${needAlert}">${displayName}</span>' +
                '<span class="contract-width60" style="color:${needAlert}">${channelName}</span>' +
                '<span class="contract-width120" style="color:${needAlert}">${copyrightEndTime}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${isPurchase}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${pagePublishStatus}</span>' +
                '</div>';

            var _ppsClientArr = [
                "ANDRIOD_PPSControl",
                "ANDROID_PAD_PPSControl",
                "IOS_JAILBREAK_PPSControl",
                "IPAD_PPSControl",
                "IPHONE_PPSControl",
                "MAC_PPSControl",
                "PC_CLIENT_PPSControl",
                "WIN8_PPSControl",
                "WINDOWS_PHONE_PPSControl"
            ];

            var _platClientArr = [
                "ANDRIOD_PPS",
                "ANDROID_PAD_PPS",
                "IOS_JAILBREAK_PPS",
                "IPAD_PPS",
                "IPHONE_PPS",
                "MAC_PPS",
                "PC_CLIENT_PPS",
                "WIN8_PPS",
                "WINDOWS_PHONE_PPS"
            ];

            var platformRefer = "platformRefer",
                platSettings = "platSettings",
                platforms = "platforms";

            var title = {
                qipuId: '奇谱ID',
                displayName: '显示名称',
                channelName: '频道',
                copyrightEndTime: '版权到期时间',
                isPurchase: '是否付费',
                pagePublishStatus: '发布状态'
            };

            var checkPlatforms = [];
            Ancestor.Dao.getType({
                type: 'PlayPlatform'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_TYPE = json.data;
                    checkPlatforms = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });


            Ancestor.Dao.getType({
                type: 'PlatformRefer'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_REFER = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });

            var decodePlayPlatform = function(elementChild) {
                var locationControl = null;
                var platformObject = {
                    platName: null,
                    locationArr: []
                }
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function(indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function(j, child) {
                                if(child.hasOwnProperty("province_id")){
                                    if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            };

            var checkPPSClient = function(data) {
                if (data.qipuId == '奇谱ID') {
                    data['needAlert'] = 0;
                    return data;
                }

                var ppsCheckList = [];
                $.each(_ppsClientArr, function(i, ppsKey) {
                    if (!data.hasOwnProperty(ppsKey) || data[ppsKey] == 0) {
                        ppsCheckList.push(ppsKey);
                    }
                });

                if (ppsCheckList.length > 0) {
                    data['needAlert'] = 'red';
                } else {
                    data['needAlert'] = 'black';
                }
                return data;
            };

            var checkQipuData = function(data) {
                var playControlArr = data.QIPUDATA.access_play_control;
                if ($.isArray(playControlArr)) {
                    var temp = {};
                    $.each(playControlArr, function(index, elementChild) {
                        var platformObject = decodePlayPlatform(elementChild);
                        if (platformObject.platName != null) {
                            temp[platformObject.platName] = platformObject;
                        }
                    });

                    var qipuPlatformData = [];
                    var qipuRegionData = [];
                    var hintMsgObj = {
                        missQIYIClient: false,
                        missPPSClient: false,
                        missQIYIRegion: false,
                        missPPSRegion: false
                    };
                    $.each(checkPlatforms, function(index, element) {
                        var ppsFlag = element.val.indexOf("PPS") !== -1;
                        if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                            qipuPlatformData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSClient = true;
                            } else {
                                hintMsgObj.missQIYIClient = true;
                            }
                        }
                        if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                            qipuRegionData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSRegion = true;
                            } else {
                                hintMsgObj.missQIYIRegion = true;
                            }
                        }
                    });

                    if (hintMsgObj.missPPSClient || hintMsgObj.missQIYIClient) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.RED;
                    } else if (hintMsgObj.missPPSRegion || hintMsgObj.missQIYIRegion) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.ORANGE;
                    } else {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;
                    }

                }

                return data;
            };

            var getHtmlByData = function(data) {

                if (typeof(data.copyrightEndTime) == "number" || typeof(data.copyrightBeginTime) == "number") {

                    if (data.copyrightEndTime == '-100' || data.copyrightBeginTime == '-100') {
                        data.copyrightEndTime = "永久版权";
                    } else if (new Date() > data.copyrightEndTime || new Date() < data.copyrightBeginTime) {
                        data.copyrightEndTime = "过期";
                    } else {
                        data.copyrightEndTime = Com.date.format(new Date(data.copyrightEndTime), "yyyy-MM-dd hh:mm:ss");
                    }
                }

                //if(data.copyrightEndTime=="过期")
                //  return '';

                switch (data.isPurchase) {
                    case 0:
                    case -100:
                        data.isPurchase = "免费";
                        break;
                    case 1:
                        data.isPurchase = "收费";
                        break;
                    case undefined:
                        data.isPurchase = ""
                        break;

                    default:
                        data.isPurchase = data.isPurchase + ""
                }

                switch (data.pagePublishStatus) {
                    case 0:
                        data.pagePublishStatus = "未发布";
                        break;
                    case 1:
                        data.pagePublishStatus = "已发布";
                        break;
                    case 2:
                        data.pagePublishStatus = "页面下线";
                        break;
                    case 3:
                        data.pagePublishStatus = "页面备用"
                        break;
                    case undefined:
                        data.pagePublishStatus = ""
                        break;

                    default:
                        data.pagePublishStatus = data.pagePublishStatus + "";
                }

                var htmls = [];
                data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;

                if (data.hasOwnProperty('QIPUDATA')) {
                    data = checkQipuData(data);
                } else {
                    data = checkPPSClient(data);
                }

                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));

                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                //url: 'http://lego.iqiyi.com/suggest/simple-video-area',
                url: 'http://lego.iqiyi.com/apis/search/search-area',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                needFetchMore: true,
                needPreProcess: true,
                otherParam: $.extend({
                    t: 0,
                    filter_GTL_qipuId: 0,
                    //filter_EQI_contentType:1,
                    //'page.orderBy': "createTime",
                    //'page.order': "desc",
                    filter_GEL_duration: 30000,
                    //filter_EQI_pagePublishStatus:1,
                    //filter_INI_isPurchase : "0,-100",
                    //filter_GTI_copyrightOwnerId : 0,
                    //filter_EQI_PadIosControl:1,
                    //filter_EQI_PhoneAndroidControl:1,
                    //filter_EQI_PhoneIosControl:1,
                    //filter_EQI_PcControl:1,
                    //filter_EQI_TvControl:1,
                    //filter_EQI_PcClientControl:1,
                    //filter_EQI_H5Control:1,
                    //filter_EQI_PadAndroidControl:1,
                    //filter_EQI_PadWebControl:1,
                    //region:1,
                    'page.pageSize': 10
                        //                    filter_EQI_ANDRIOD_PPSControl: 1,
                        //                    filter_EQI_ANDROID_PAD_PPSControl: 1,
                        //                    filter_EQI_IOS_JAILBREAK_PPSControl: 1,
                        //                    filter_EQI_IPAD_PPSControl: 1,
                        //                    filter_EQI_IPHONE_PPSControl: 1,
                        //                    filter_EQI_MAC_PPSControl: 1,
                        //                    filter_EQI_PC_CLIENT_PPSControl: 1,
                        //                    filter_EQI_WIN8_PPSControl: 1,
                        //                    filter_EQI_WINDOWS_PHONE_PPSControl: 1,
                        //                    needCookie: true

                    //   pps region 限制
                    //region_ANDROID_PAD_PPS:0,
                    //region_WIN8_PPS:0,
                    //region_MAC_PPS:0,
                    //region_WINDOWS_PHONE_PPS:0,
                    //region_ANDRIOD_PPS:0,
                    //region_IOS_JAILBREAK_PPS:0,
                    //region_IPAD_PPS:0,
                    //region_IPHONE_PPS:0,
                    //region_PC_CLIENT_PPS:0,
                    //   qiyi region 限制
                    //region_ANDROID_PAD_IQIYI:1,
                    //region_ANDROID_PHONE_IQIYI:1,
                    //region_H5_QIYI:1,
                    //region_IOS_PAD_IQIYI:1,
                    //region_IOS_PHONE_IQIYI:1,
                    //region_PAD_WEB_QIYI:1,
                    //region_PC_CLIENT_IQIYI:1,
                    //region_PC_QIYI:1,
                    //region_TV_IQIYI:1,
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'filter_LIKES_displayName': term
                    };
                },

                fetchMore: function(data, callback) {
                    var self = this;
                    self.count = 0;
                    self.ret = [];
                    self.data = data;
                    $.each(data, function(i, item) {
                        Ancestor.Dao.getQipuDataById(item, function(json, t) {
                            if (json) {
                                t.QIPUDATA = json;
                            }
                            self.ret.push(t);
                            self.count++;
                            if (self.count == self.data.length) {
                                callback(self.ret);
                            }
                        });
                    });
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data.result, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.displayName,
                                id: item.qipuId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-backup');
        };

        var alternatePlayCollectionSuggest = function($inputs, options) {
            $inputs.each(function(index, element) {
                var self = this;
                alternatePlayCollection($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.qipuId);
                        //console.log( $input.data('value'));

                        var temp = data.item;
                        data.item = {};

                        data.item['qipuId'] = temp['qipuId'];
                        data.item['displayName'] = temp['displayName'];
                        data.item['contentType'] = temp['contentType'];
                        data.item['duration'] = temp['duration'];
                        data.item['needAlert'] = temp['needAlert'];
                        temp = {};

                        var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val();
                        //console.log(alternatePlayCollection);
                        if (alternatePlayCollection) {
                            alternatePlayCollection = JSON.parse(alternatePlayCollection);
                            var has = false,
                                i;

                            for (var i in alternatePlayCollection) {
                                if (alternatePlayCollection[i].qipuId == data.item.qipuId) {
                                    has = 1;
                                    break;
                                }
                            }

                            i = parseInt(i) + 1;

                            if (!has) {
                                var msg = null;
                                if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                                } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                                } else {
                                    alternatePlayCollection[i] = data.item;

                                    $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                    alternatePlayCollectionAppend({
                                        qipuId: data.item.qipuId
                                    });
                                }

                                if (msg) {
                                    SystemDialog.queryConfirm(msg, function(flag) {
                                        if (flag === true) {
                                            alternatePlayCollection[i] = data.item;

                                            $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                            alternatePlayCollectionAppend({
                                                qipuId: data.item.qipuId
                                            });
                                        }
                                    });
                                }
                            }

                        } else {
                            alternatePlayCollection = {};

                            var msg = null;
                            if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                            } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                            } else {
                                alternatePlayCollection[0] = data.item;

                                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                alternatePlayCollectionAppend({
                                    qipuId: data.item.qipuId
                                });
                            }

                            if (msg) {
                                SystemDialog.queryConfirm(msg, function(flag) {
                                    if (flag === true) {
                                        alternatePlayCollection[0] = data.item;

                                        $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                        alternatePlayCollectionAppend({
                                            qipuId: data.item.qipuId
                                        });
                                    }
                                });
                            }
                        }
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };


        var alternatePlayCollectionAppend = function(v) {
            $('#alternatePlayCollectionIds').append('<span class="ui-suggest-value tagmanagerTag" data-id="' + v.qipuId + '">' + v.qipuId + '<a class="tagmanagerRemoveTag"  onclick="Ancestor.Util.removeAlternatePlayCollection(this)"  title="Remove" href="javascript:;">x</a></span>');
            $('input[name="alternatePlayCollectionInput"]').attr('disabled','disabled');;
        };

        // 删除备播库
        removeAlternatePlayCollection = function(obj) {

            var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val(),
                AlternatePlayCollectionId = $(obj).parent().attr('data-id'),
                alternatePlayCollectionTmp = {};

            alternatePlayCollectionTmp = alternatePlayCollection = JSON.parse(alternatePlayCollection);

            for (var i in alternatePlayCollectionTmp) {
                if (alternatePlayCollectionTmp[i].qipuId == AlternatePlayCollectionId) {
                    delete alternatePlayCollection[i];
                    break;
                }
            }

            if ($.isEmptyObject(alternatePlayCollection)) {
                $('input[name="alternatePlayCollection"]').val('');
                $('input[name="alternatePlayCollectionInput"]').removeAttr('disabled');;
            } else {
                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
            }

            $(obj).parent().remove();
        };



        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            imageCrop: imageCrop,
            authorization: authorization,
            getParam: getParam,
            getUrlId: getUrlId,
            fillFieldNameWhenChangeSelect: fillFieldNameWhenChangeSelect,
            limitWordCount: limitWordCount,
            getUploadFiles: getUploadFiles,
            isNormal: isNormal,
            openDlg: openDlg,
            qitanSuggest: qitanSuggest,
            universalCodeSuggest: universalCodeSuggest,
            imageObjectEcho: imageObjectEcho,
            getAuth: getAuth,
            alternatePlayCollectionSuggest: alternatePlayCollectionSuggest,
            alternatePlayCollectionAppend: alternatePlayCollectionAppend,
            removeAlternatePlayCollection: removeAlternatePlayCollection,
        };


    })();

});
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 * 
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../ancestor/Ancestor.Grid',['require','exports','module'],function(require, exports, module) {

    Ancestor.Grid = function(options) {};
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        filterDataWhenBatchOper: function(data, filter) {
            filter = filter || function(item) {
                return !item.del;
            };

            data = $.grep(data, function(item) {

                return filter(item);
            });

            return data;
        },
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function(callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [{
                page: 1
            }]);

        },
        getParam: function() {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function() {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function() {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGrid: function() {
            return this.$grid;
        },

        run: function(options, callback) {


            this.bindEvent();
            this.echoQuery();
            this.initGrid.call(this, options, callback);

        },

        setType: function(type) {
            this.options.type = type;
        },

        getType: function() {
            return this.options.type;
        },

        getGridConfig: function(table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function(i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function(options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        bindEvent: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');

            /*
             * 绑定时间
             *
             */
            //$.datepicker.setDefaults( $.datepicker.regional[ "" ] );

            $container.find("#StartTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#EndTime").datepicker("option", "minDate", selectedDate);
                }

            });

            $container.find("#EndTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#StartTime").datepicker("option", "maxDate", selectedDate);
                }
            });

            $form.find('button[type="reset"]').click(function() {
                self.resetQueryForm();
            });
        },

        resetQueryForm: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');
            // 从suggest获得的数据都需要清空
            $form.find('input[data-key]').removeAttr('data-id');
        },

        reload: function(params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        },

        // 基本数据请求队列
        ajaxBasicRequestQueue: (function() {
            var Queue = [];

            var pushData = function(obj) {
                Queue.push(obj);
            };
            var getQueueLen = function() {
                return Queue.length;
            };
            var getQueueData = function() {
                return Queue;
            };
            var clearQueueData = function() {
                Queue = [];
            };

            return {
                pushData: pushData,
                getQueueLen: getQueueLen,
                getQueueData: getQueueData,
                clearQueueData: clearQueueData
            };

        })(),

        ajaxBasicRequestLen: -1,
        intverId: null,

        // 处理请求队列
        ajaxBasicRequestManage: (function() {

            var self = null,
                fct = null,
                tryNumbers = 10000; //尝试10000次

            var init = function(obj, func) {
                self = obj;
                fct = func;
                start();
            };

            var start = function() {
                var len = self.ajaxBasicRequestQueue.getQueueLen();
                if (len === 0) return;

                if (self.ajaxBasicRequestLen == len || tryNumbers == 1) {
                    clearInterval(self.intverId);
                    fct(self);
                    self.ajaxBasicRequestQueue.clearQueueData();
                } else if (self.ajaxBasicRequestLen != -1) {
                    return;
                } else {
                    var queue = self.ajaxBasicRequestQueue.getQueueData();
                    self.ajaxBasicRequestLen = 0;

                    $.each(queue, function(i, item) {
                        item.func(function() {
                            self.ajaxBasicRequestLen++;
                        });
                    });
                    self.intverId = setInterval(start, 10);
                }
                tryNumbers--;
            };
            return {
                init: init
            };
        })(),
    });

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../ancestor/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var config = Ancestor.Config;

            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // 获取配频道配置数据
            var getType = function(data, callback) {
                var options = {
                    url: config.CONFIGS_API.url,
                    dataType: 'json',
                    data: data,
                    method: 'get',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/configs");

            };

            var getSuggestData = function(url, data, callback) {

                var request = {};
                request.url = url;
                request.type = 'get';

                if (data.needCookie)
                    request.needCookie = true;

                request.params = data;

                data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, '/redirect');
            };

            var getQipuDataById = function(item, callback) {
                var url = Ancestor.Config.QIPU_URL.replace("${QIPUID}", item.qipuId);

                var request = {};
                request.url = url;
                request.type = 'get';

                var data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    method: 'post',
                    data: data,
                    success: function(data) {
                        callback.call(this, data, item);
                    },
                    error: function(data) {
                        callback.call(this, data, item);
                    }
                };

                ajax(options, '/redirect');
            };

            // 获取分类
            var getuniversalCodeData = function(url, data, callback) {

                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, url.split('api')[1]);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var qichuanUploadFile = function(data, handler) {
                var self = this;
                var xhr = _getXHR();
                var precent = 0;
                xhr.open('POST', data.url, true);
                // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                for (var key in data.headers) {
                    xhr.setRequestHeader(key, data.headers[key]);
                }

                xhr.upload.onprogress = function(e) {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (e.lengthComputable) {
                        precent = (e.loaded / e.total) * 100;
                        if (handler.onProgress) {
                            handler.onProgress.apply(self, [precent, data]);
                        }
                    }
                };

                xhr.onreadystatechange = function() {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (xhr.readyState == 4) {
                        var stat = xhr.status;
                        if ((stat >= 200 && stat < 300) || stat == 304 || stat == 1223 || stat === 0) {
                            if (handler.onFinish) {
                                handler.onFinish.call(self, data);
                            }
                        } else {
                            if (handler.onFail) {
                                handler.onFail.call(self, data);
                            }
                        }
                    }
                };

                var formData = new FormData();
                formData.append('businessType', data.headers['businessType']);
                formData.append('fileid', data.headers['file_id']);
                formData.append('imagefile', data.file);

                // xhr.send(data.file || null);
                xhr.send(formData);


                return xhr;
            };


            var qichuanRequestFile = function(options, callback) {
                options = options || {};
                var headers = options.headers || {};

                var options = {
                    url: options.url + '?t=' + new Date().getTime(),
                    // url: options.url,
                    dataType: 'json',
                    // data: data,
                    headers: headers,
                    method: 'get',
                    success: function(data) {
                        if (data && data.code == 'A00000') {
                            callback.call(this, data);
                        } else {
                            console.log('get access fail.');
                            callback.call(this, data);
                        }
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, false);

            };

            var platSettings = function(options, callback) {
                var options = {
                    url: '/api/channel/getPlatSettings',
                    dataType: 'json',
                    data: options,
                    method: 'post',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/channel/getPlatSettings");
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                getType: getType,
                qichuanRequestFile: qichuanRequestFile,
                qichuanUploadFile: qichuanUploadFile,
                getSuggestData: getSuggestData,
                platSettings: platSettings,
                getuniversalCodeData: getuniversalCodeData,
                getQipuDataById: getQipuDataById,
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Upload.js
 * @path:   js-src/upload/
 * @desc:   基于HTML5的上传的核心组件，基于奇传的接口
 *
 * @author: lichunping@qiyi.com
 * @date:   2013-05-15
 *
 */
define('../ancestor/Ancestor.Upload',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Upload = function(options) {
        this.dao = Ancestor.Dao;
        this.config = Ancestor.Config;
        options = options || {};

        this.options = $.extend(true, {

            // 如果想支持想支持多文件需在外再封装一层
            file: null,

            uploadHost: null,
            // finishUrl: '/upload',
            // cancelUrl: '/cancelupload',

            requestURL: this.config.QICHUAN.image_requestURL_test,
            uploadURL: this.config.QICHUAN.image_uploadURL_test,

            deviceId: this.config.QICHUAN.deviceId,

            // 开始时间
            startTime: 0,

            role: 'epg_image',
            businessType: 'image',
            producttype: 'ppc',

            // spath: null,
            currentDate: null,
            // openAuthInfo: null,

            // 请求文件完成
            onRequest: function(data) {},
            // 开始发送数据
            onStart: function(data) {},
            // 上传成功
            onFinish: function(data) {},
            // 上传暂停
            onPause: function(data) {},
            // 上传恢复
            onResume: function(data) {},
            // 上传过程回调，每个分片
            onProgress: function(data) {},
            // 取消上传
            onCancel: function(data) {},
            // 上传失败
            onFail: function(data) {},
            // 上传出现错误
            onError: function(data) {}

        }, options);

        // 模拟构造方法，在实例化执行
        // 根据自己的需要加入需要初始化执行的内容
        this.construct = options.construct || function() {
            this.init();
        };

        // 放在最下方立即执行
        this.construct.call(this);
    };

    Ancestor.Upload.prototype = {

        init: function() {
            var self = this;
            var _options = self.options;

            /*
            var isNormalUser = User.Util.isNormal();
            if(!_options.uploadURL) {
                if(isNormalUser) {
                    _options.uploadURL = this.config.QICHUAN.image_uploadURL;
                } else {
                    _options.uploadURL = this.config.QICHUAN.inner_image_uploadURL;
                }
            }
            */
        },

        /**
         * 用于更新options内容，继承选项，覆盖相同属性
         * @param {Object} options  选项
         */
        update: function(options) {
            this.options = $.extend(true, this.options, options);
        },

        getUID: function() {
            return Com.string.createUUID();
        },

        getFile: function() {
            return this.options.file;
        },

        getUploadHost: function(url) {
            var self = this;
            if (this.uploadHost) {
                return this.uploadHost;
            }
            url = url || self.options.uploadUrl;
            if (!url || url.length <= 0) {
                return null;
            }
            // 含http://, 不是 Com.url.host(url);
            return url.substr(0, url.lastIndexOf('/'));
        },

        getFileType: function(name) {
            return Com.file.getFileType(name);
        },


        getDeviceId: function() {
            return this.options.deviceId;
        },

        getFilePath: function() {
            return this.options.role + this.options.spath;
        },


        getRequestFileOptions: function(options) {
            var self = this;
            var _options = self.options;
            options = options || {};
            var file = options.file || self.getFile();
            var currentDate = _options.currentDate || Com.date.getCurrentDate();
            var openAuthInfo = options.openAuthInfo || {};
            var access_token = openAuthInfo.access_token || self.getAccessToken();
            var fileUID = file.uid || self.getUID();

            // must be required the file info, authorize info
            if (!file.size || !access_token) {
                console.log('is not file or access_token.');
                return null;
            }

            options = {
                role: options.role || _options.role,
                // 奇传改为2.0后，请求file时不再传递spath
                // spath: options.spath ||  ( currentDate + '/' + fileUID
                //         + '.' + Com.file.getExt(file.name) ),
                spath: options.spath,
                filesize: file.size,
                filetype: Com.file.getExt(file.name),
                access_token: access_token
            };

            return options;
        },

        /*
        options = {
            url: requestURL, // optional
            data: {
                role: 角色,  // optional
                access_token: 认证, // optional
                filesize: 文件尺寸, // required
                spath: 文件存储路径, // optional
                device_id: 客户端UID // optional
            }
        }
        */
        requestFile: function(options, callback) {
            var self = this;
            var _options = self.options;
            options = options || {};

            var params = {
                url: options.url || _options.requestURL,
                headers: {
                    filetype: Com.file.getExt(options.file.name),
                    filesize: options.file.size,
                    role: options.file.role || _options.role,
                    location: options.file.location || _options.location,
                    producttype: options.file.producttype || _options.producttype,
                    businessType: options.file.businessType || _options.businessType
                }
            };

            var _callback = function(data) {
                if (data && data.code == 'A00000') {
                    callback.call(this, data);
                } else {
                    _options.onError.call(self, data);
                }
                if (_options.onRequest) {
                    _options.onRequest.call(self, data);
                }
            };

            return self.dao.qichuanRequestFile(params, _callback);
        },

        send: function(options, handler) {
            //        var self = this;
            handler = handler || {};
            var $xhr = $.ajax({
                url: options.url,
                processData: false,
                dataType: 'json',
                headers: options.headers,
                contentType: 'application/x-www-form-urlencoded',
                // contentType: false,
                data: options.file,
                method: 'POST',

                beforeSend: function(data) {
                    if (handler.onBeforeSend) {
                        handler.onBeforeSend.call(this, data);
                    }
                },
                success: function(data) {
                    if (handler.onFinish) {
                        handler.onFinish.call(this, data);
                    }
                },
                complete: function(data) {
                    if (handler.onComplete) {
                        handler.onComplete.call(this, data);
                    }
                },
                error: function(data) {
                    if (handler.onError) {
                        handler.onError.call(this, data);
                    }
                }
            });

            return $xhr;
        },



        uploadFile: function(options, callback) {

            var self = this;
            var _options = self.options;
            options = options || {};

            var data = options.data;

            var file = _options.file || self.getFile();
            var params;
            var handler = {
                onFail: _options.onFail,
                onError: _options.onError,
                onProgress: _options.onProgress
            };

            file.file_id = data.file_id;

            params = {
                url: file.upload_url || _options.uploadURL,
                file: file,
                headers: {
                    file_id: file.file_id,
                    file_size: file.size,
                    range: data.range || ('0' + '-' + (file.size - 1) + ''),
                    businessType: _options.businessType
                }
            };

            // 直接上传，完成后回调
            handler.onFinish = function(data) {

                if (!$.isPlainObject(data)) {
                    data = $.parseJSON(data);
                }
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            return self.dao.qichuanUploadFile(params, handler);
        },

        // 一个文件的片段上传完成后，发起结束通知
        finishUpload: function(options, handler) {
            var self = this;
            handler = handler || {};
            options = options || {};
            var _options = self.options;
            var file = options.file || self.getFile();
            var params = null;
            var access_token = options.access_token || self.getAccessToken();
            params = {
                contentType: 'application/json',
                url: options.url,
                headers: {
                    access_token: access_token,
                    file_id: file.file_id,
                    range_finished: 'true'
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });
        },

        startUpload: function(options, handler) {
            var self = this;
            var _options = self.options;
            options = options || {};

            handler = options.handler;

            if (options.file) {
                _options.file = options.file;
            }

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onStart.call(self, data);
                    self.uploadFile(data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.requestFile(options, callback);

        },

        cancelUpload: function(options) {
            var self = this;
            var _options = self.options;
            handler = handler || {};
            var file = options.file || _options.file;
            var cancelUrl = self.getUploadHost() + '' + _options.cancelUrl;
            var params = {
                url: cancelUrl,
                headers: {
                    // 按照奇传接口定义取消参数
                    access_token: options.access_token || self.getAccessToken(),
                    file_id: file.file_id,
                    status: 2
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onCancel.call(self, data);
                } else {
                    data.errorMsg = 'onCancel error.';
                    _options.onCancel.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });

        }
    };


});

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },

            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
                var _defaultHandler = function(msg){
                    EpgWeb.Plugin.showTips({type: "error", content: msg})
                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Channel.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2013-01-07
 */
define(
    '../channel/Channel',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Channel = window.Channel || {
            version: '1.0'
        };


    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Action.js
 * @path:   js-src/Channel/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
define(
    '../channel/Channel.Action',['require','exports','module'],function(require, exports, module) {


        Channel.Action = (function() {

            // 表格
            var channelGrid = null;
            var channelEditForm = null;



            var getChannelGrid = function(options) {

                if (!channelGrid) {
                    channelGrid = new Channel.Grid($.extend(true, {
                        '$container': $('#ChannelListContainer'),
                        type: 0
                    }, options));
                }

                return channelGrid;

            }

            var channelGridRun = function(options) {

                channelGrid = getChannelGrid(options);
                channelGrid.run();

                console.log('grid run');

            }

            // 频道列表
            var run = function() {

                Ancestor.Config.EPG_AUTH.list = '/channel/list';
                channelGridRun({});

            }

            // 频道新建/编目
            var editRun = function() {
                channelEditRun({});



            }

            var channelEditRun = function(options) {

                channelEditForm = getChannelEdit(options);
                channelEditForm.run();
                console.log('channelEditRun run');

            }

            function getChannelEdit(options){
                if (!channelEditForm) {
                    channelEditForm = new Channel.Edit($.extend(true, {
                        '$container': $('.channel-edit-form'),
                        type: 0
                    }, options));
                }
                return channelEditForm;
            }

            return {
                run: run,
                editRun: editRun,
                getChannelGrid: getChannelGrid
            }
        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Config.js
 * @path:   js-src/Channel/
 * @desc:   Channel公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
///import js-src/lib/
///import js-src/com/
define('../channel/Channel.Config',['require','exports','module'],function (require, exports, module) {
    Channel.Config = $.extend({}, Ancestor.Config, {
        PLAY_TYPE: ["未知", "点播", "直播"],

        SEARCH: {

            rules: {
                qipuId: {

                    digits: true
                }


            },


            messages: {
                "qipuId": {
                    "digits": "请输入正确的奇谱ID"
                }
            }

        },


        EDIT: {

            rules: {
                name: {
                    required: true,
                    maxlength: 40
                },
                //  shortName: {required:true,maxlength:10},
                universalCode: {
                    required: true,
                    alphaNumber: true
                },

                maxPlaybackPeriod: "required",
                logoUrl: "required",
                carousel_table_no: {
                    required: true,
                    digits: true
                }
            },


            messages: {
                "name": {
                    "required": "直播频道名称不能为空",
                    "maxlength": "最多输入40个字符"
                },

                "universalCode": {
                    "required": "节目单代码不能为空",
                    "alphaNumber": "请输入正确的节目单代码"
                },

                /* "shortName":{
                 "required": "频道简称不能为空",
                 "maxlength":"最多输入10个字符"
                 },



                 "type":{
                 "required": "频道类型不能为空"
                 },

                 "qitanId":{"digits": "请输入正确的奇谈ID"},


                 "orderBy":{
                 "required": "频道排序不能为空",
                 "digits": "请输入正确的排序"
                 },*/

                "maxPlaybackPeriod": {
                    "required": "最大回看时间不能为空"
                },
                /*
                 "ppsBaikeId":{"digits": "请输入正确的pps百科id"},
                 */
                "logoUrl": {
                    "required": "请上传频道图标"
                },
                "carousel_table_no": {
                    "digits": "请输入正确的轮播台台号",
                    "required": "轮播台台号不能为空"
                    //  "isExists" : "此轮播台台号已存在,请换一个"
                }
            },

            onkeyup: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onkeyup: true
                };

                if (typeof cb.onkeyup == 'function') {
                    cb.onkeyup($element, this);
                } else if (cb.onkeyup) {
                    $element.valid();
                }
            },
            onfocusout: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onfocusout: true
                };

                if (typeof cb.onfocusout == 'function') {
                    cb.onfocusout($element, this);
                } else if (cb.onfocusout) {
                    $element.valid();
                }
            }


        },

        TABLE_COLMODEL_CONFIG: {
            id: {
                name: 'id',
                index: 'id',
                title: false,
                width: 100,
                align: 'center',
                sortable: false
            },

            qipuId: {
                name: 'qipuId',
                index: 'qipuId',
                title: false,
                width: 80,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.qipuId(v, r);
                }
            },
            name: {
                name: 'name',
                index: 'name',
                width: 120,
                align: 'center',
                title: false,
                sortable: false,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.name(v, r);
                }
            },

            liveType: {
                name: 'liveType',
                index: 'liveType',
                title: false,
                width: 80,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.liveType(v, r);
                }

            },


            type: {
                name: 'type',
                index: 'type',
                title: false,
                width: 80,
                sortable: false,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.channelType(v, r);
                }
            },

            universalCode: {
                name: 'universalCode',
                index: 'universalCode',
                title: false,
                width: 70,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.universalCode(v, r);
                }

            },

            defaultLogoUrl: {
                name: 'defaultLogoUrl',
                index: 'defaultLogoUrl',
                title: false,
                sortable: false,
                width: 100,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.defaultLogoUrl(v, r);
                }

            },

            maxPlaybackPeriod: {
                name: 'maxPlaybackPeriod',
                index: 'maxPlaybackPeriod',
                width: 80,
                align: 'center',
                sortable: false,
                title: false,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.maxPlaybackPeriod(v, r);
                }
            },

            isEnable: {
                name: 'isEnable',
                title: false,
                sortable: false,
                width: 60,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.isEnable(v, r);
                }
            },
            isMemeberFree: {
                name: 'isMemeberFree',
                sortable: false,
                title: false,
                width: 60,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.isMemeberFree(v, r);
                }
            },

            status: {
                name: 'status',
                sortable: false,
                title: false,
                width: 70,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.status(v, r);
                }
            },

            operate: {
                name: 'operate',
                width: 210,
                sortable: false,
                title: false,
                align: 'center',

                formatter: function (v, o, r) {
                    return Channel.Util.formatter.operate(v, r);
                }

            },

            addTime: {
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 120,
                align: 'center'
            },


            operator: {
                name: 'operator',
                index: 'operator',
                sortable: false,
                title: false,
                width: 60,
                align: 'center',
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.operator(v, r);
                }
            },
///
            log_id: {
                name: 'id',
                index: 'id',
                title: false,
                sortable: false,
                hidden: true
            },
            log_addTime:{
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            log_user: {
                name: 'user',
                index: 'user',
                sortable: false,
                title: false,
                width: 150
            },
            log_type: {
                name: 'type',
                index: 'type',
                sortable: false,
                title: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Channel.Util.formatter.log_type(v, r);
                }
            },
            log_descr: {
                name: "descr",
                index: 'descr',
                title: false,
                width: 450,
                sortable: false
            }
        },
        TABLE: { //素材库查询列表配置
            url: '/api/channel/list',
            //datatype:"jsonp",
            multiselect: false,

            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 10,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "奇谱ID", "频道名称", "直播类型", "频道类型", "节目单代码", "logo",
                "回看时间", "启用状态", "划价状态", "操作",
                "创建日期", "操作历史"
            ],

            colModel: ['id', 'qipuId', 'name', 'liveType', 'type', 'universalCode', 'defaultLogoUrl', 'maxPlaybackPeriod',
                'isEnable', 'status', 'operate', 'addTime', 'operator'
            ]
        },

        TABLE_LOG: {
            url: "/api/channel/loglist",
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 50,
            mtype: "post",
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/channel/loglist");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "操作时间", "人员", "动作", "备注"],
            colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
            pager: "#log_pager"
        },

        SLICE_DELAY_CHECK: {
            msg: '修改延时时间后需要手动修改节目单时间',
            oldValue: null,
            headUrl: null
        },

        AUTOMATION_TYPE: {
            0: "手动节目单",
            1: "自动化节目单(专辑)",
            2: "自动化节目单(节目)"
        },

        USER_COUNT: {
            0: "小于5w",
            1: "5-30w",
            2: "30-100w",
            3: "大于100w"
        },

        /* alternatePlayCollection remote api */
        APC_CONFIG: (function () {
            var prefix = auth.dev() ? 'http://10.10.5.161:50002/' : 'http://bake.produce.qiyi.domain:50002/';
            return {
                apc_add: prefix + "add",
                apc_delete: prefix + "delete",
                apc_info: prefix + "info"
            }
        })(),
        AUTH_CHECK: {
            technologist: false
        },
        TempChannel:null,
        NormalChannel:null,
        Carousel:null
    });
});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Dao.js
 * @path:   js-src/Channel/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-07
 */
define(
    '../channel/Channel.Dao',['require','exports','module'],function(require, exports, module) {

        Channel.Dao = $.extend({}, EpgWeb.Dao, {

            // 频道添加
            setChannelAddData: function(data, callback) {
                var options = {
                    url: '/api/channel/create',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/create');
            },

            // 频道修改
            setChannelModifyData: function(data, callback) {
                var options = {
                    url: '/api/channel/edit',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/edit');
            },

            // 频道删除
            deleteChannelData: function(data, callback) {
                var options = {
                    url: '/api/channel/del',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/del');
            },

            // 获取单个频道数据
            getSingleChannelData: function(data, callback) {
                var options = {
                    url: '/api/channel/get',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/get');
            },

            // 获取分类
            getCategories: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/redirect');
            },


            // 频道操作历史
            getOperateLog: function(data, callback) {
                var options = {
                    url: '/api/channel/loglist',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/loglist');
            },

            //{control":0,"stream":0,"program":0}

            /*  
                program >0 节目单 直播流管理    
                stream >0 直播流管理  播控中心
                control > 0  播控中心 预约计划
                */

            // 获取频道操作权限
            getChannelAuth: function(data, callback) {
                var options = {
                    url: '/api/channel/menuShow',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/menuShow');
            },

            // 获取某天节目单
            getProgramListByDay: function(data, callback) {
                var options = {
                    url: '/api/program/list',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/list');
            },

            // 获取某天节目单
            getPreviewStream: function(data, callback) {
                var options = {
                    url: '/api/channel/getPreviewStream',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/getPreviewStream');
            },

            // 轮播台台号是否存在
            carouselTableNo: function(data, callback) {
                var options = {
                    url: '/api/channel/carouselTableNo',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/carouselTableNo');
            },

            // 备播库调用第三方接口
            alternateOperation: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/redirect');
            },

            getProgramMaxDuration: function (data, callback) {
                var options = {
                    url: '/api/program/maxDuration',
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data)
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/maxDuration');
            }
        });
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Base.js
 * @path:   js-src/Channel/
 * @desc:   Channel模块下基础业对象类
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define(
    '../channel/Channel.Grid',['require','exports','module'],function(require, exports, module) {


        Channel.Grid = function(options) {
            this.dao = Channel.Dao;
            this.config = Channel.Config;
            this.options = options || {};
        };

        Com.inherits(Channel.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
                self._initBasicData();
            },
            fillGridByUrl: function() {
                var channelName = Ancestor.Util.getUrlId("channelName");
                if (channelName != null && channelName.length != 0) {
                    $("input[name='name']").val( decodeURIComponent(channelName) );
                }
            },

            run: function() {
                var self = this;
                self.fillGridByUrl();
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LiveChannelType',
                            cfgName: 'CHANNEL_TYPE',
                            errMsg: '频道类型获取失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LiveType',
                            cfgName: 'LIVE_TYPE',
                            errMsg: '直播类型获取失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });
                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                        Channel.Util.getType({
                            type: 'LogType',
                            cfgName: 'LOG_TYPE',
                            errMsg: '获取日志类型失败',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });

                this.ajaxBasicRequestQueue.pushData({
                    func: function(ajaxBasicRequestLen) {
                       auth.getAuthData({tips:1,url: '/epg/env_config_list.html'},function (rt) {
                           if (rt == null) {
                             //   this.config.AUTH_CHECK.sys_config = true;
                               $("a[name=configslink]").show();
                           }
                           ajaxBasicRequestLen()
                       })
                    }
                });

                this.ajaxBasicRequestManage.init(this, function(obj) {
                    obj.start();
                });

            },

            start: function(options, callback) {
                var self = this;
                self.init();

                var gridConfig = self.getGridConfig();
                //self.echoQuery();

                options = $.extend(true, {
                    // width: 1500,
                    //  shrinkToFit: false,
                    //autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);

                $('body').on('click', 'a.disabled', function(e) {
                    e.preventDefault();
                });

                $('#resetFrm').click(function() {
                    $('select[name="type"]').html('<option value="">请选择</option>');
                    $('select[name="type"]').hide();
                });
            },


            _initBasicData: function() {

                var html = '';
                $.each(Channel.Config.LIVE_TYPE, function(i, n) {
                    if (n != undefined) {
                        html += '<option value="' + i + '">' + n + '</option>';
                    }

                });

                $('select[name="liveType"]').append(html);



                Channel.Config.NormalChannel = {},
                    Channel.Config.TempChannel = {},
                    Channel.Config.Carousel = {};

                $.each(Channel.Config.CHANNEL_TYPE, function(i, n) {

                    if (n != undefined) {
                        if (n.indexOf("临时") == -1) {
                            if (n.indexOf("爱奇艺") == -1)
                                Channel.Config.NormalChannel[i] = n;
                            else
                                Channel.Config.Carousel[i] = n;
                        } else {
                            Channel.Config.TempChannel[i] = n;
                        }
                    }

                });

            },

            initGrid: function(options, callback) {
                var self = this;
                var params = self.getParam();

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');
                //params.rowNum=10;

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                    postData: $.extend(true, {}, params),

                }, gridConfig, options);

                //   $grid.jqGrid('scroll', {});

                //console.log(options   );

                $grid.jqGrid(options);

            },
            jsonConvert: function(jsonstr, o) {
                if (jsonstr && typeof jsonstr === 'string') {
                    var _jsonparse = false;
                    if ($.jgrid.useJSON) {
                        $.jgrid.useJSON = false;
                        _jsonparse = true;
                    }
                    var json = $.jgrid.parse(jsonstr);
                    if (_jsonparse) {
                        $.jgrid.useJSON = true;
                    }
                    var gprm = json[o.jsonGrid.config];
                    var jdata = json[o.jsonGrid.data];
                    if (jdata) {
                        var svdatatype = gprm.datatype;
                        gprm.datatype = 'jsonstring';
                        gprm.datastr = jdata;
                        $($t).jqGrid(gprm).jqGrid("setGridParam", {
                            datatype: svdatatype
                        });
                    } else {
                        $($t).jqGrid(gprm);
                    }
                }
            },
            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                /*
                Channel.Config.TABLE.jsonReader ={  

                     root:"data.result",  

                     page: "data.pageNo",  

                     total: "data.totalCount/data.pageSize",  

                     records: "data.totalCount",

                 };
*/

                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },


            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function() {
                    return true; //this.name; 
                });

                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';

                    }

                });

                return params;

            },

            bindEvent: function() {
                var self = this;
                self.bindBasicEvent();
            },


            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    var validator = Channel.Util.getValidator($form, Channel.Config.SEARCH);

                    if (!validator.form())
                        return;

                    self.query();
                    return false;
                });

                $("div.query").keydown(function(event) {
                    if (event.keyCode == 13) {
                        var validator = Channel.Util.getValidator($form, Channel.Config.SEARCH);
                        if (!validator.form())
                            return;

                        self.query();
                        return false;
                    }
                });

                $form.find('button[type="reset"]').click(function() {
                    self.resetQueryForm();
                });

                $('select[name="liveType"]').click(function() {

                    var html = '<option value="">请选择</option>';

                    if ($(this).val() == 1) {
                        $.each(Channel.Config.NormalChannel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });

                    } else if ($(this).val() == 2) {
                        $.each(Channel.Config.TempChannel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                    } else if ($(this).val() == 3) {
                        $.each(Channel.Config.Carousel, function(i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                    } else {
                        html = '';
                    }

                    if (html != '') {
                        $('select[name="type"]').show();
                    } else
                        $('select[name="type"]').hide();

                    $('select[name="type"]').html(html);

                });
            },

            bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "minDate", selectedDate);
                    },

                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "maxDate", selectedDate);
                    },

                });

                fillFieldNameWhenChangeSelect($form, 'query-select-control', 'query-input-text');
            },

        });

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../channel/Channel.Task',['require','exports','module'],function (require, exports, module) {
        Channel.Task = $.extend({}, EpgWeb.Task, {
            getLiveChannelType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },
            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            },
            getLiveType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            }
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2013-01-07
 */
define(
    '../channel/Channel.Edit',['require','exports','module'],function (require, exports, module) {
        Channel.Edit = function (options) {
            this.dao = Channel.Dao;
            this.config = Channel.Config;
            this.task = Channel.Task;
            this.options = options || {};
        };

        Com.inherits(Channel.Edit, {}).extend({
            run: function () {
                var self = this;
                var taskArr = [];
//                taskArr.push(self.task.getConfigType(self.dao.cfgName.liveChannelType));
//                taskArr.push(self.task.getConfigType(self.dao.cfgName.LiveType));
//                taskArr.push(self.task.getConfigType("InterruptType"));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    //  console.log("channel edit init over");
                    self.init();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            init: function () {
                var self = this;
                var $container = self.options.$container;
                Channel.Util.bindDatetimepicker([$container.find('input[name="tempStartTime"]'),
                    $container.find('input[name="tempEndTime"]'),
                    $container.find('input[name="paidStartTime"]'),
                    $container.find('input[name="paidEndTime"]')
                ]);

                this.bindEditEvent($container);
                //描述字数限制
                Ancestor.Util.limitWordCount($('.channel-edit-form textarea[name="description"]'), 300);
                Ancestor.Util.qitanSuggest($('input.qitanSuggest'));
                Ancestor.Util.alternatePlayCollectionSuggest($('input.alternatePlayCollectionSuggest'));
            },
            // 绑定频道编辑事件
            bindEditEvent: function ($container) {
                // 节目单代码验证方法
                jQuery.validator.addMethod("alphaNumber", function (value, element) {

                        var re = new RegExp("^([a-z]|[A-Z])+[0-9]*[\-]*[0-9]*([a-z]|[A-Z])*$");
                        return re.test(value);
                    }, ""
                );
                this._editBindEvent();
                this._liveTypeLinkage();
                Channel.Util._initEditData($container);
                Channel.Util._initEditEvent();
            },
            _editBindEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $submit = $container.find('#Submit');
                var id = Channel.Util._getChannelId('id');

                if (id == null)
                    document.title = "频道新增";
                else
                    document.title = "频道修改";

                var validator = Channel.Util.getValidator($container, Channel.Config.EDIT);
                $submit.on('click', function () {
                    // 提交前验证
                    if (!validator.form())
                        return;
                    if ($.trim($("#ctn-tps").text()) != "") {
                        if (id != null && Stream.Config.ctn == $('input[name="carousel_table_no"]').val()) {
                        } else {
                            $(document).tips({
                                content: "轮播台台号重复！",
                                type: "error"
                            });
                            return;
                        }
                    }
                    var data = Channel.Util.getParam($container);
                    if (data.liveType === '3') {
                        if (!Channel.Util.checkAutomationType(data['automation'])) {
                            $(document).tips({  content: "请选择正确的节目单类型。", type: "error" });
                            return;
                        }
                        if ($('input[name="alternatePlayCollection"]').val().length == 0) {
                            $(document).tips({  content: "请添加备播库节目", type: "error" });
                        }
                        if ($('input[name="tag"]').val().length == 0) {
                            $(document).tips({  content: "请设置大小写分类", type: "error" });
                        }
                    }
                    if (!Channel.Util.checkSubjectUrl(data)) {
                        $(document).tips({
                            content: "专题页url格式错误,请修改后保存.",
                            type: "error"
                        });
                        return;
                    }

                    if (!Channel.Util.checkMaxPlaybackPeriod(data)) {
                        $(document).tips({
                            content: "最大回看时间不允许大于48小时,请修改后保存.",
                            type: "error"
                        });
                        return;
                    }

                    $(this).attr("disabled", "disabled");

                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });

                    Channel.Config.SLICE_DELAY_CHECK.data = data;
                    // 检验压流延时的修改
                    Channel.Util.checkSliceDelay();
                    return;
                });
                Channel.Util.imageCrop($('#AlbumEditScreenCorp'));
                $('input[name="isMemeberFree"]').on('click.radio', function () {
                    if ($('input[name="isMemeberFree"]:checked').val() == 0) {
                        $('#isMemeberFree').show();
                    } else {
                        $('#isMemeberFree').hide();
                    }
                });
                $('input[name="formal"]').on('click.radio', function () {
                    var categoryWarn = $('#category-warn');
                    var tagshow = $('span.tagshow');
                    var tag = $('input[name="tag"]');
                    if ($('input[name="formal"]:checked').val() == 0) {
                        tagshow.attr("record", tagshow.text());
                        tagshow.attr("recordTag", tag.val());
                        tagshow.text("正在直播_临时直播");
                        tag.val("200003919_200978719");
                        categoryWarn.css("display", "inline-block");
                    } else {
                        tagshow.text(tagshow.attr("record"));
                        tag.val(tagshow.attr("recordTag"));
                        categoryWarn.css("display", "none");
                    }
                });
            },
            _liveTypeLinkage: function (id) {
                $('select[name=type]').bind("change", function (e) {
                    if ($(this).val() == 5 || $(this).val() == 11) {
                        Channel.Dao.carouselTableNo({
                            carousel_table_no: $(".channel-edit-form").find("input[name=carousel_table_no]").val(),
                            type: $(this).val(),
                            channelId: Ancestor.Util.getUrlId('id')
                        }, function (json) {
                            if (json.code == 'A00000') {
                                $("#ctn-tps").text(json.msg).show();
                            } else {
                                $("#ctn-tps").text("").hide();
                            }
                        });
                    }
                });
                $('select[name="liveType"]').bind("change", function (event) {
                    var html = '';
                    if ($(this).val() == 1) {
                        $.each(Channel.Config.NormalChannel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                        $('#ucode').show();
                        $('#ucode').find('[name="universalCode"]').removeAttr('disabled');
                        $("#alternatePlayCollectionIdsGroup").hide();
                        $("#carouselTableNo").html("").hide();
                        $("#sDelay").hide();
                        $("#isTest").hide();
                        $("#subjectUrlGroup").hide();
                        $("#automationBlock").hide();
                    } else if ($(this).val() == 2) {
                        $.each(Channel.Config.TempChannel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });

                        $('#ucode').hide();
                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                        $("#alternatePlayCollectionIdsGroup").hide();
                        $("#carouselTableNo").html("").hide();
                        $("#sDelay").show();
                        $("#isTest").show();
                        $("#subjectUrlGroup").show();
                        $("#automationBlock").hide();
                        $("#category-control-div").hide();

                    } else if ($(this).val() == 3) {
                        $.each(Channel.Config.Carousel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                        $('#ucode').hide();
                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                        $("#alternatePlayCollectionIdsGroup").show(); // 备播库显示
                        Channel.Util._writeCarouselTableNoHtml("");
                        $("#sDelay").hide();
                        $("#isTest").hide();
                        $("#subjectUrlGroup").hide();
                        $("#automationBlock").show();
                        $("#category-control-div").show();
                    }
                    $('select[name="type"]').html(html);
                });
            }
        })

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Util.js
 * @path:   js-src/Channel/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../channel/Channel.Util',['require','exports','module'],function(require, exports, module) {

    Channel.Util = $.extend(true, {}, Ancestor.Util, {

        // jqGrid formater relative method 
        formatter: {
            qipuId: function(v, r) {
                if (dev)
                    return '<a href="http://qipu-test.qiyi.domain/int/entity/nocache/' + r.qipuId + '.json" target="_blank">' + r.qipuId + '</a>';//<br />老奇谱ID:<a href="http://qipu-test.qiyi.domain/int/entity/nocache/' + r.oldQipuId + '.json" target="_blank">' + r.oldQipuId + '</a>';
                else
                    return '<a href="http://qipu.qiyi.domain/int/entity/nocache/' + r.qipuId + '.json" target="_blank">' + r.qipuId + '</a>';//<br />老奇谱ID:<a href="http://qipu.qiyi.domain/int/entity/nocache/' + r.oldQipuId + '.json" target="_blank">' + r.oldQipuId + '</a>';
            },

            name: function(v, r) {

                return '<div style="word-wrap : break-word;word-break:break-all;"><a href="' + r.pageUrl + '" target="_blank">' + r.name + '</a></div>';

            },

            liveType: function(v, r) {
                return Channel.Config.LIVE_TYPE[r.liveType];

            },

            universalCode: function(v, r) {
                if (r.liveType == 1)
                    return '<a href="http://www.tvmao.com/api/EpgDataServlet?secret=Gee6S5dQ&c=' + r.universalCode + '" target="_blank">' + r.universalCode + '</a>';
                else
                    return '';
            },

            defaultLogoUrl: function(v, r) {
                if (r.defaultLogoUrl == undefined)
                    return '生产中...';
                else
                    return '<a target="_blank" href="' + r.defaultLogoUrl + '"><img height="25px" width="60px" src="' + r.defaultLogoUrl + '"></a>';
            },

            maxPlaybackPeriod: function(v, r) {
              return Number(v / 3600).toFixed(2) * 100 / 100 + '小时';
            },

            channelType: function(v, r) {

                return Channel.Config.CHANNEL_TYPE[r.type];
            },

            operate: function(v, r) {
                var htmls = [];
                var name = r.name;

                htmls.push('<div class="oper">');

                if (r.isEnable === -1) {
                    htmls.push('<a class="disabled">预览</a>');
                    htmls.push('<a class="disabled">编目</a>');
                    htmls.push('<a class="disabled">节目单</a>');
                    htmls.push('<a class="disabled">直播流管理</a>');
                    htmls.push('</br>');
                    htmls.push('<a class="disabled">播控中心</a>');
                    //htmls.push('<a class="disabled">预约计划</a>');
                    htmls.push('<a class="disabled">删除</a>');
                    htmls.push('</div>');
                    return htmls.join('');
                }


                if (r.menuShow != undefined) {

                    var program = '',
                        stream = 'disabled',
                        broadcast = 'disabled',
                        reserve = 'disabled';

                    var json = JSON.parse(r.menuShow);


                    if (json.program > 0) {
                        stream = '';
                        if (json.stream > 0) {
                            broadcast = '';
                            if (json.control > 0) {
                                reserve = '';
                            }
                        }
                    }

                }

                if (broadcast == '') {

                    if (!r.alternatePlayCollection)
                        r.alternatePlayCollection = '';

                    htmls.push('<a href="javascript:;" data-id="' + r.id + '" data-type="' + r.liveType + '" data-alternatePlayCollection=\'' + r.alternatePlayCollection + '\' data-qipu-id="' + r.qipuId + '" onclick="Channel.Util.preview(this);">预览</a>');
                } else
                    htmls.push('<a href="javascript:;" class="disabled" data-id="' + r.id + '">预览</a>');
                htmls.push('<a href="./channel_edit.html?id=' + r.id + '" target="_blank">编目</a>');

                var delDisabled = '';

                if (r.liveType == 3) {
                    htmls.push('<a href="./carousel_edit.html?fatherId=' + r.id + '" class="' + program + '" target="_blank">节目单</a>');
                } else
                    htmls.push('<a href="./program_list.html?fatherId=' + r.id + '" class="' + program + '" target="_blank">节目单</a>');


                htmls.push('<a href="./live_stream.html?qipuId='+ r.qipuId+'&id=' + r.id + '&name=' +  encodeURIComponent(name.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase() + '" class="' + stream + '" target="_blank">直播流管理</a>');
                htmls.push('</br><a href="./broadcast_manager.html?id=' + r.id + '&name=' + name + '" class="' + broadcast + '" target="_blank">播控中心</a>');
                //htmls.push('<a href="./reservation_list.html?id=' + r.id + '&name=' + name + '" class="' + reserve + '" target="_blank">预约计划</a>');
                //htmls.push('<a href="javascript:;" >禁用</a>');

                if (r.liveType != 3 || auth.dev())
                    htmls.push('<a href="javascript:;" onclick="Channel.Util.deleteChannel(' + r.id + ');" >删除</a>');
                //htmls.push('<a href="javascript:;" >预览直播流</a>');

                htmls.push('</div>');
                return htmls.join('');
            },

            isEnable: function(v, r) {
                if (r.isEnable === 1) {
                    return '启用';
                } else if (r.isEnable === -1) {
                    return '已删除';
                } else {
                    return '未启用';
                }
            },

            isMemeberFree: function(v, r) {
                if (r.isMemeberFree) {
                    return '免费';
                } else {
                    return '收费';
                }
            },

            status: function(v, r) {

                switch (r.status) {
                    case 'PAIED_AVAILABLE':
                        return '付费已划价';
                        break;

                    case 'PAIED_NOT_AVAILABLE':
                        return '付费未划价';
                        break;

                    case 'FREE':
                        return '免费';
                        break;

                }
            },


            operator: function(v, r) {
                return '<a href="javascript:;" data-id="' + r.id + '" onclick="Channel.Util.operateHistory(this);">详细</a>';
            },
            log_type:function(v, r ){
                return Channel.Config.LOG_TYPE[r.type];
            }
        },

        // 绑定时间控件
        bindDatetimepicker: function(obj) {

            try {
                for (var i in obj) {
                    $(obj[i]).datetimepicker({
                        onClose: function(selectedDate) {
                            $(obj[i]).find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                        }

                    });
                }
            } catch (e) {}

        },



        _initEditEvent: function() {
            var self = this;

            // 分类对话框
            $("#category-a").click(function() {
                if ($('input[name="formal"]:checked').val() == 1) {
                    self.showCategoriesDlg();
                    self._showHasSelectedCat();
                }
            });

            $(".channel-edit-form").on("input propertychange", "[name='carousel_table_no']",
                function() {
                    Channel.Dao.carouselTableNo({
                        carousel_table_no: $(this).val(),
                        type: $(".channel-edit-form").find("select[name=type]").val(),
                        channelId: Ancestor.Util.getUrlId('id')
                    }, function(json) {

                        if (json.code == 'A00000') {

                            $("#ctn-tps").text(json.msg).show();

                        } else {
                            $("#ctn-tps").text("").hide();

                        }
                    });
                });



            $("#categories-dlg").on('dblclick', '.parent_category', function() {

                if ($(this).val() > 0) {
                    var title = $(".parent_category").find("option:selected").text();
                    var id = $(".parent_category").val() + '_0';

                    var tmp = $("#category-val>span");

                    var seq = null;
                    $.each($(tmp), function() {

                        if ($(this).attr('data-tag-id') == id)
                            seq = true;

                    });

                    var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                    if (!seq)
                        $("#category-val").append(tag_span);

                }

            });

            // 大小分类事件绑定
            $("#categories-dlg").on('change', '.parent_category', function() {

                var pcObj = $(this);
                var parent_cate_id = $(this).val()[0];

                var sub_cate = $('.sub_category');
                var options = '';
                if (parent_cate_id > 0) {

                    var request = self.genCategoriesRequestStr(parent_cate_id);

                    Channel.Dao.getCategories({
                        request: request
                    }, function(json) {

                        sub_cate.empty();
                        $.each(json, function(i, item) {
                            options += '<option value="' + item.id + '">' + item.name + '</option>';
                        });
                        sub_cate.html(options);

                        sub_cate.unbind("dblclick").bind("dblclick", function() {
                            var tmp = $("#category-val>span");

                            if ($(this).val() > 0) {
                                var title = $(".parent_category").find("option:selected").text() + '_' + $(this).find("option:selected").text();
                                var id = $(".parent_category").val() + '_' + $(this).val();
                            } else {
                                var title = $(".parent_category option:selected").text();
                                var id = $(".parent_category").val() + '_' +0;
                            }

                            var seq = null;
                            $.each($(tmp), function() {

                                if ($(this).attr('data-tag-id') == id)
                                    seq = true;

                            });

                            var tag_span = $('<span data-tag-id="' + id + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + title + '">' + title + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');

                            if (!seq)
                                $("#category-val").append(tag_span);

                        });

                    });

                }
            });


            $('input[name=maxPlaybackPeriod]').blur(function() {
                var val = $(this).val();

                if(isNaN(val)) {
                    $('#mpp-tps').text('最大回看时间必须为数字').show();
                    return;
                }else{
                    $('#mpp-tps').text('').hide();
                }

                var channelId = self._getChannelId("id");

                if(channelId == null) {
                    return;
                }

                Channel.Dao.getProgramMaxDuration({fatherId: channelId}, function (json) {
                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '获取节目信息失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {
                        if (json.data !== "") {
                            var programInfo = json.data;
                            programInfo = programInfo.replace(/'/gm, "\"");
                            programInfo = JSON.parse(programInfo);
                            if (programInfo.duration > val*3600) {
                                $('#mpp-tps').text('最大回看时间需要大于等于' + self.formatter.maxPlaybackPeriod(programInfo.duration, null)).show();
                            }else{
                                $('#mpp-tps').text('').hide();
                            }
                        }else{
                            $('#mpp-tps').text('').hide();
                        }
                    }
                });
            });


        },
        _getChannelId: function(id) {
            return this.getUrlId(id);
        },

        _initLiveChannelType: function($container) {
            var self = this;

            // 频道类型
            Channel.Dao.getType({
                type: 'LiveChannelType'
            }, function(json) {
                if (json.code == 'A00000') {
                    Channel.Config.NormalChannel = {},
                    Channel.Config.TempChannel = {};
                    Channel.Config.Carousel = {};
                    $.each(json.data, function(i, n) {
                        if (n.val.indexOf("临时") == -1) {
                            if (n.val.indexOf("爱奇艺") == -1 && n.val != '台湾台')
                                Channel.Config.NormalChannel[n.key] = n.val;
                            else
                                Channel.Config.Carousel[n.key] = n.val;
                        } else
                            Channel.Config.TempChannel[n.key] = n.val;
                    });

                    var html = '';
                    $.each(Channel.Config.NormalChannel, function(i, n) {
                        html += '<option value="' + i + '">' + n + '</option>';
                    });

                    $container.find('select[name="type"]').html(html);
                    self._initInterruptType($container);

                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }
            });


        },


        _initLiveType: function($container) {
            var self = this;
            // 直播类型
            Channel.Dao.getType({
                type: 'LiveType'
            }, function(json) {
                if (json.code == 'A00000') {


                    var html = '';
                    $.each(json.data, function(i, n) {
                        html += '<option value="' + n.key + '">' + n.descr + '</option>';
                    });

                    $container.find('select[name="liveType"]').html(html);

                    self._initLiveChannelType($container);

                } else {
                    var msg = Channel.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }

            });


        },

        _initAutomation: function($container, index) {
            var self = this;
            var html = '<option value="">请选择</option>';
            var data = Channel.Config.AUTOMATION_TYPE;
            $.each(data, function(i) {
                html += '<option value="' + i + '">' + data[i] + '</option>';
            });

            $container.find('select[name="automation"]').html(html);
        },

        _initUserCount: function($container, index) {
            var self = this;
            var html =  '';
            var data = Channel.Config.USER_COUNT;
            $.each(data, function(i) {
                html += '<option value="' + i + '">' + data[i] + '</option>';
            });
            $container.find('select[name="userCount"]').html(html);
        },


        _initInterruptType: function($container) {

            var self = this;
            // 播放器提示信息
            Channel.Dao.getType({
                type: 'InterruptType'
            }, function(json) {
                if (json.code == 'A00000') {
                    var html = '';
                    $.each(json.data, function(i, n) {
                        html += '<option value="' + n.key + '">' + n.descr + '</option>';
                    });
                    $container.find('select[name="interruptHintType"]').html(html);
                    self._initChannelData($container)
                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = '播放器提示信息获取失败';
                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }

            });

        },

        _writeCarouselTableNoHtml: function(value) {
            var self = this;
            self.carouselTableNoVal = value;
            auth.getAuthData({
                tips: 1,
                url: '/epg/carousel_table_no.html'
            }, function(rt) {

                if (!rt) {
                    $("#carouselTableNo").html('<label class="control-label" for="">轮播台台号<span class="form-must">*</span>：</label>' + '<div class="controls">' + '  <input type="text" name="carousel_table_no" value="' + self.carouselTableNoVal + '" placeholder="台号为整数类型" />' + '<span id="ctn-tps" style="color:red"></span>' + '</div>').show(); // 轮播台台号显示
                }
            });
        },

        _initChannelData: function($container) {

            var self = this;

            // 隐藏收费起止时间
            $('#isMemeberFree').hide();

            // 隐藏压流延时
            $("#sDelay").hide();

            $("#isTest").hide();

            //隐藏专题页url
            $("#subjectUrlGroup").hide();

            //隐藏节目单类型选择
            $("#automationBlock").hide();

            //隐藏节目单类型选择
            $("#automationBlock").hide();

            // 修改时加入id
            var id = this._getChannelId('id');

            if (id != null) {
                $container.append('<input type="hidden" name="id" value="">');

                // 检测是否存在流（限制压流延时是否可修改）
                Stream.Dao.getStreamInfo({
                    'fatherId': id
                }, function(json) {
                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '获取频道流信息失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {
                        var hasFLVorHCDN = false;
                        if (json.data.length != 0) {
                            $('#sDelay').find('[name="sliceDelay"]').attr('disabled', 'disabled');
                            //TODO 添加压流延时禁止修改提示
                            //$('#sDelayTip').html('');
                        }

                        $.each(json.data, function() {
                            if (this.formatType === "FLV" || this.formatType === "HCDN" || this.formatType === 'HLFLV') {
                                hasFLVorHCDN = true;
                            }
                        });

                        if(hasFLVorHCDN) {
                            $('#userCountBlock').find('[name="userCount"]').attr('disabled', 'disabled');
                        }
                    }
                });

                Channel.Dao.getSingleChannelData({
                    'id': id
                }, function(json) {

                    if (json.code == 'undefined' || json.code != 'A00000') {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = '初始化频道修改数据失败';

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    } else {

                        // 初始化频道数据
                        var $form = $container;

                        var $elements = $.makeArray($form.prop('elements')).filter(function() {
                            return true; //this.name;
                        });

                        // 保存压流延时原始值
                        Channel.Config.SLICE_DELAY_CHECK.oldValue = json.data.sliceDelay;

                        var name;
                        var key;
                        var hasInit = {};


                        $.each($elements, function() {
                            name = this.name;

                            var value = json.data[name];

                            var liveType = 0;

                            if (this.type == "radio") {

                                if (!hasInit[name]) {
                                    $.each($('input[name="' + this.name + '"]'), function() {

                                        if ($(this).val() == value) {
                                            $(this).prop("checked", true);
                                        } else {
                                            $(this).prop("checked", false);
                                        }
                                    });

                                    hasInit[name] = 1;
                                }

                            } else {

                                if (this.name == 'tag') {

                                    var ids = [];
                                    var tags = json.data[name].split(',');

                                    for (var i = 0; i < tags.length; i++) {
                                        ids.push(tags[i]);
                                    }


                                    self.getParentCategories(ids, function(data) {

                                        self.getSubCategories(data, function() {
                                            $('.tagshow').text(self.subCategories.join(','));

                                        });
                                    });



                                    if (value == 2) {
                                        $("#sDelay").show();
                                        $("#isTest").show();
                                    }

                                }

                                if (this.name == 'logoUrl') {
                                    self.imageObjectEcho($form, value);
                                    //$('.cropimg').html('<img src="' + value + '">');
                                }

                                if (this.name == 'maxPlaybackPeriod') {
                                    value = Number(value / 3600).toFixed(2) * 100 / 100;
                                }


                                $(this).val(value);

                                if (this.name == 'automation') {
                                    $('[name="automation"]').attr('disabled', 'disabled');
                                }

                                if (this.name == 'liveType') {

                                    $('[name=liveType]').attr('disabled', 'disabled');

                                  //  $('#ucode').val('');

                                    if (value == 2 || value == 3) {
                                        $('#ucode').hide();
                                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                                        $('select[name="liveType"]').change();
                                        if (value == 3) {
                                            Channel.Util._writeCarouselTableNoHtml(json.data["carouselTableNo"]);
                                            Stream.Config.ctn = json.data["carouselTableNo"];
                                        }
                                    }

                                    if (value != 3) {
                                        $("#alternatePlayCollectionIdsGroup").hide();
                                    }else{
                                        $("#automationBlock").show();
                                    }

                                    if (value == 2) {
                                        $("#sDelay").show();
                                        $("#isTest").show();
                                    }
                                    liveType = value;
                                }
                                if (this.name == 'description') {
                                    //描述字数限制
                                    Ancestor.Util.limitWordCount($('.channel-edit-form textarea[name="description"]'), 300);
                                }


                                if (this.name == 'alternatePlayCollection' && value) {
                                    var v = JSON.parse(value);

                                    for (var i in v) {

                                        Ancestor.Util.alternatePlayCollectionAppend(v[i]);

                                    }
                                }

                                if(this.name == 'type' && (value == 5 || value == 11)) {
                                    $('[name=type]').attr('disabled', 'disabled');
                                }

                            }

                        });

                        if (json.data["formal"] == 0 && json.data["liveType"] == 2) {
                            $('#category-warn').css("display", "inline-block");
                        }
                    }


                });

            }else{
                $("select[name=liveType]").change();
            }

        },

        // 根据分类id或取对应中文
        getSubCategories: function(ids, callback) {

            var self = this;

            if (ids == '') {
                callback.call(this);
                return;

            }

            var pop_id = ids.shift();

            var _id = pop_id.split('_');

            var pName = '',
                sName = '';

            var request = this.genCategoriesRequestStr(_id[0]);

            Channel.Dao.getCategories({
                request: request
            }, function(json) {

                for (var i = 0; i < Channel.Config.PCAT.length; i++) {
                    if (Channel.Config.PCAT[i].id == _id[0]) {
                        pName = Channel.Config.PCAT[i].name;
                        break;
                    }
                }

                for (var i = 0; i < json.length; i++) {
                    if (json[i].id == _id[1]) {
                        sName = json[i].name;
                        break;
                    }
                }

                if (!sName)
                    self.subCategories.push(pName);
                else
                    self.subCategories.push(pName + '_' + sName);

                self.getSubCategories(ids, callback);

            });


        },


        // 初始化编辑数据修改
        _initEditData: function($container) {
            this._initAutomation($container);
            this._initUserCount($container);
            this._initLiveType($container);
        },

        // 显示已选分类
        _showHasSelectedCat: function() {

            var tags = $('.tagshow').text().split(',');
            var ids = $('input[name="tag"]').val().split(',');
            var tag_span = '';

            if (tags == '') return;

            $.each(tags, function(i, item) {

                tag_span = tag_span + '<span data-tag-id="' + ids[i] + '" class="ui-suggest-value tagmanagerTag" data-tag-label="' + item + '">' + item + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>';

            });

            $("#category-val").append(tag_span);

        },



        checkAutomationType: function(automation){
            return !(automation !== '1' && automation !== '0' && automation !== '2');
        },

        numMulti: function (n1, n2) {
            var baseNum = 0;
            try {
                baseNum += n1.toString().split(".")[1].length;
            } catch (e) {
            }
            try {
                baseNum += n2.toString().split(".")[1].length;
            } catch (e) {
            }
            return Number(n1.toString().replace(".", "")) * Number(n2.toString().replace(".", "")) / Math.pow(10, baseNum);
        },

        checkSubjectUrl: function (data) {
            if (data.hasOwnProperty('subjectUrl') && data.subjectUrl !== '') {
                return data.subjectUrl.split('://')[0] === 'http';
            }
            return true;
        },

        checkAPC: function() {
            var self=this;
            var data = Channel.Config.SLICE_DELAY_CHECK.data;
            // 校验备播库奇谱ID
            if ($("#alternatePlayCollectionIdsGroup").is(":visible") && self._getChannelId('id') != null) {
                self.callApcAPI(data);

            } else {
                self.apcFinalOperation(data);
            }

        },

        checkSliceDelay: function() {
            var self=this;
            var data = Channel.Config.SLICE_DELAY_CHECK.data;
            var newValue = data.sliceDelay;
            var oldValue = Channel.Config.SLICE_DELAY_CHECK.oldValue + '';

            if(!self._getChannelId('id')){
                Channel.Config.SLICE_DELAY_CHECK.headUrl = './channel.html';
                self.checkAPC();
                return;
            }

            if(oldValue && newValue !== oldValue){
                SystemDialog.queryConfirm(Channel.Config.SLICE_DELAY_CHECK.msg, function(flag){
                    if(flag){
                        Channel.Config.SLICE_DELAY_CHECK.headUrl =  './program_list.html?fatherId=' + Channel.Util._getChannelId('id');
                        self.checkAPC();
                    }else{
                        var submit = $.find('#Submit')[0];
                        submit.disabled = '';
                        $(document).tips({
                            content: "频道信息未保存",
                            type: "error"
                        });
                    }
                });
            }else{
                Channel.Config.SLICE_DELAY_CHECK.headUrl = './channel.html';
                self.checkAPC();
            }
        },

        checkMaxPlaybackPeriod: function(data) {
            if (data.hasOwnProperty('maxPlaybackPeriod')) {
                var a = data.maxPlaybackPeriod;
                // 最大回看时间 2*24
                if (a > 48) {
                    return false;
                }
            }
            return true;
        },

        checkMaxPlayBackPeriodWithProgramMaxDuration: function (data, id) {
            var self = this;
            Channel.Dao.getProgramMaxDuration({fatherId: id}, function (json) {
                if (json.code == 'undefined' || json.code != 'A00000') {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = '获取节目信息失败';

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                } else {
                    if (json.data !== "") {
                        var programInfo = json.data;
                        programInfo = programInfo.replace(/'/gm, "\"");
                        programInfo = JSON.parse(programInfo);
                        if (programInfo.duration > data.maxPlaybackPeriod) {
                            var msg = "存在节目[" + programInfo.name + "] 时长[" + self.formatter.maxPlaybackPeriod(programInfo.duration, null) + "]大于填写的最大回看时长，请重新填写!";
                            $(document).tips({
                                content: msg,
                                type: "error"
                            });

                            var submit = $.find('#Submit')[0];
                            submit.disabled = '';

                            return;
                        }
                    }

                    Channel.Dao.setChannelModifyData(data, self.onSave); // 修改
                }
            });
        },

        apcFinalOperation: function(data) {
            var self = this;

            // transfer maxPlaybackPeriod to seconds
            if (data.hasOwnProperty('maxPlaybackPeriod')) {
                var a = data.maxPlaybackPeriod;
                a = self.numMulti(a, 3600);
                data.maxPlaybackPeriod = a;
            }

            var id = self._getChannelId('id');
            if (id == null) {
                Channel.Dao.setChannelAddData(data, self.onSave); // 新增
            }else{
                self.checkMaxPlayBackPeriodWithProgramMaxDuration(data, id);
                //Channel.Dao.setChannelModifyData(data, self.onSave); // 修改
            }
        },

        apcErrorOperation: function() {
            var self = this;
            var submit = $.find('#Submit')[0];
            submit.disabled = '';

            $(document).tips({
                content: "备播库节目信息保存出错, 请稍候重试！",
                type: "error"
            });
        },

        apcAdd: function(data, formData) {
            var self = this;
            var request = {};
            var addList = data[0];

            if (addList.length == 0) {
                self.apcFinalOperation(formData);
                return;
            }

            request.url = Channel.Config.APC_CONFIG.apc_add;
            request.type = 'get';
            request.params = {
                channelids: Ancestor.Util.getUrlId('id'),
                qiPuIds: addList.join(',')
            };
            request = JSON.stringify(request);

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();

                } else if (json.error_code == '0') {
                    console.log('调用成功' + json);

                    self.apcFinalOperation(formData);
                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();
                }

            });
        },

        apcDelete: function(data, formData) {
            var self = this;
            var request = {};
            var deleteList = data[1];

            if (deleteList.length == 0) {

                setTimeout(function() {
                    self.apcAdd(data, formData);
                }, 3000);

                return;
            }

            request.url = Channel.Config.APC_CONFIG.apc_delete;
            request.type = 'get';
            request.params = {
                channelids: Ancestor.Util.getUrlId('id'),
                qiPuIds: deleteList.join(',')
            };
            request = JSON.stringify(request);

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();
                } else if (json.error_code == '0') {
                    console.log('调用成功' + json);

                    setTimeout(function() {
                        self.apcAdd(data, formData);
                    }, 3000);

                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();
                }

            });
        },

        callApcAPI: function(formData) {
            var self = this;
            var request = {};

            request.url = Channel.Config.APC_CONFIG.apc_info;
            request.type = 'get';
            request.params = {
                channelid: Ancestor.Util.getUrlId('id')
            };
            request = JSON.stringify(request);

            //  var beforeApcOperation = this.beforeApcOperation;

            Channel.Dao.alternateOperation({
                request: request
            }, function(json) {
                if (typeof(json) == "undefined") {
                    console.log("调用备播库接口失败!");
                    self.apcErrorOperation();

                } else if (json.error_code == '0') {
                    var qipuIdsNew = [];
                    var qipuIdsInfo = [];
                    var addList = [];
                    var deleteList = [];

                    if ($('input[name="alternatePlayCollection"]').val() != '') {

                        var tempData = JSON.parse($('input[name="alternatePlayCollection"]').val());
                        $.each(tempData, function(key, value) {
                            var qipuId = value.qipuId;
                            qipuIdsNew.push(qipuId);
                        });
                    }

                    if (json.info != "") {
                        info = json.info.replace('\{', '').replace('\}', '').split(',');
                        $.each(info, function(key, value) {
                            qipuIdsInfo.push(Number(value));
                        });
                    }
                    var tempList = $.unique($.merge($.merge([], qipuIdsNew), qipuIdsInfo));

                    $.each(tempList, function(key, val) {
                        if ($.inArray(val, qipuIdsNew) < 0) {
                            deleteList.push(val);
                        }

                        if ($.inArray(val, qipuIdsInfo) < 0) {
                            addList.push(val);
                        }
                    });

                    self.apcDelete([addList, deleteList], formData);
                } else {
                    console.log("获取备播库信息错误!");
                    self.apcErrorOperation();

                }

            });

        },

        save: function(data) {

        },
        onSave: function(json) {
            if (json.code == 'A00000') {
                var url = Channel.Config.SLICE_DELAY_CHECK.headUrl;

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);

                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {

                $('#Submit').removeAttr("disabled");

                var msg = Stream.Config.REQUEST_FAIL;
                if (json.msg != undefined)
                    msg = json.msg;

                $(document).tips({
                    content: msg,
                    type: "error"
                });
            }

        },

        genCategoriesRequestStr: function(father_id) {
            var request = {};
            request.url = 'http://xinqi.if.iqiyi.com/basic/categories.json';
            request.type = 'get';
            request.params = {
                father_id: father_id
            };

            return JSON.stringify(request);
        },

        showCategoriesDlg: function() {

            var $container = $("#categories-dlg");

            $container.dialog({
                title: '对应列表分类',
                appendTo: null,
                modal: true,
                width: 450,
                //  height:380,
                //      maxHeight: 380,
                position: ['top', 'top+20'],
                buttons: [{
                    text: '确定', //  提交分类
                    click: function() {

                        var tags = [],
                            ids = [];


                        $.each($("#category-val").find('span'), function() {

                            ids.push($(this).attr("data-tag-id"));
                            tags.push($(this).attr("data-tag-label"));
                        });
                        //console.log(ids);
                        //console.log(tags);
                        var tags = $('.tagshow').text(tags.join(','));
                        var ids = $('input[name="tag"]').val(ids.join(','));

                        $(this).dialog('close');
                    }
                }, {
                    text: '取消',
                    click: function() {
                        $(this).dialog('close');
                    }
                }],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

                },
                close: function() {

                }

            });

            var $tmpl = $("#categories");

            this.getParentCategories('', function() {
                $container.html($tmpl.tmpl({
                    parentCategory: Channel.Config.PCAT
                }));
            });


        },


        // 获取大分类
        getParentCategories: function(data, callback) {
            var request = this.genCategoriesRequestStr(0);

            if (!Channel.Config.PCAT) {
                Channel.Dao.getCategories({
                    request: request
                }, function(json) {

                    Channel.Config.PCAT = json;

                    callback.call(this, data);

                });
            } else {
                callback.call(this, data);
            }

        },

        // 子分类
        subCategories: [],



        getValidator: function($container, config) {
            // var $container = this.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, config);

            return validator;
        },

        setContainer: function($container) {
            this.$container = $container;
        },

        bindChannelEvent: function() {
            var self = this;
        },

        // 历史记录
        operateHistory: function(obj) {
            var self = this;
            var id = $(obj).attr('data-id');
            auth.getAuthData({
                tips: 1,
                url: '/epg/channel_log.html'
            }, function(rt) {
                if (!rt) {
                    Channel.Config.AUTH_CHECK.technologist = true
                }
                var tableConfig = $.extend(true, {}, Channel.Config.TABLE_LOG );
                tableConfig.width = Channel.Config.AUTH_CHECK.technologist ? 875 : 425
                var colModel = tableConfig.colModel;
                var newColModel = [];
                var colModelConfig = Channel.Config.TABLE_COLMODEL_CONFIG;

                $.each(colModel, function(i, model) {
                    newColModel.push(colModelConfig[model]);
                });
                tableConfig.colModel = newColModel;
                tableConfig.colModel[4].hidden = !Channel.Config.AUTH_CHECK.technologist;
                $('#logList').jqGrid(tableConfig);
                self.openDlg($("#o-h-dlg"), '历史记录',Channel.Config.AUTH_CHECK.technologist ? 900 : 450 , 600);
                $('#logList').jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {id:id}
                }).trigger('reloadGrid');
            });
        },


        // 预览
        preview: function(obj) {
            var self = this,
                id = $(obj).attr('data-id'),
                type = $(obj).attr('data-type'),
                qipuId = $(obj).attr('data-qipu-id'),
                alternatePlayCollection = $(obj).attr('data-alternatePlayCollection'),
                $container = $('#preview');

            if (alternatePlayCollection) {
                alternatePlayCollection = JSON.parse(alternatePlayCollection);
            }

            Channel.Config.programTypeData = Channel.Config.programTypeData || {};

            if ($.isEmptyObject(Channel.Config.programTypeData)) {
                Channel.Dao.getType({
                    type: 'ContentType'
                }, function(json) {
                    if (json.code == 'A00000') {

                        $.each(json.data, function(index, element) {
                            Channel.Config.programTypeData[element.key] = element.descr;
                        });

                        if (type == 3) {
                            self._program(type, id, qipuId, alternatePlayCollection, self, $container);
                            // self._carousel(id,qipuId,alternatePlayCollection, self, $container);
                        } else {
                            self._program(type, id, qipuId, alternatePlayCollection, self, $container);
                        }

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });
                    }

                });

            } else {
                if (type == 3) {
                    this._program(type, id, qipuId, alternatePlayCollection, self, $container);
                    //this._carousel(id,qipuId,alternatePlayCollection, self, $container);
                } else {
                    this._program(type, id, qipuId, alternatePlayCollection, self, $container);
                }
            }

        },


        _flvPlayer: function(src) {
            return '<embed width="640" height="420"' +
                ' src="http://www.iqiyi.com/common/flashplayer/20141218/LivePlayer_3_0_3_4.swf" ' +
                'quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
                ' align="middle"' +
                ' play="true"' +
                ' loop="true"' +
                ' scale="showall"' +
                ' wmode="window"' +
                ' devicefont="false"' +
                ' bgcolor="#000000"' +
                ' name="player"' +
                ' menu="true"' +
                ' allowfullscreen="true"' +
                ' allowscriptaccess="always"' +
                ' flashvars="vid=' + src + '&source=live.lego.iqiyi.com&cid=qc_100001_300089"' +
                ' salign="" ' +
                'type="application/x-shockwave-flash">';

        },

        _mp4Player: function(src) {
            return '<video width=362 height=200' +
                ' id="MobileVideo" ' +
                'autoplay="autoplay"' +
                ' src="' + src + '" ' +
                'controls="controls">' +
                '您的浏览器不支持 video 标签'+
            '</video>';
        },

        // 预览节目列表
        _program: function(cType, id, qipuId, alternatePlayCollection, obj, $container) {
            var self = this;
            var currentDateArr = Com.date.getCurrentDate().split('/'),
                currentDateStr = '',
                currentDate = '';

            if (currentDateArr.length > 3) {
                currentDateArr[0] = currentDateArr[1];
                currentDateArr[1] = currentDateArr[2];
                currentDateArr[2] = currentDateArr[3];
            }

            currentDate = currentDateArr[0] + '-' + currentDateArr[1] + '-' + currentDateArr[2];
            var sendObj = {
                    startDate: currentDate + " 00:00:00",
                    endDate: currentDate + " 23:59:59",
                    fatherId: id,
                    pageSize: 400
                },
                currentDateStr = currentDateArr[0] + '年' + currentDateArr[1] + '月' + currentDateArr[2] + '日';

            // 节目列表
            Channel.Dao.getProgramListByDay(sendObj, function(json) {

                if (json.code == 'A00000') {

                    var list = {
                        am: [],
                        pm: []
                    };

                    $.each(json.data.result, function(index, element) {
                        if (cType != 3) element.live = 2;
                        json.data.result[index]['type'] = Channel.Config.PLAY_TYPE[element.live];

                        if (new Date() >= new Date(json.data.result[index]['startPlayTime']) && new Date() <= new Date(json.data.result[index]['endPlayTime']))
                            json.data.result[index]['playing'] = true;

                        if (new Date(json.data.result[index]['startPlayTime']) < new Date(currentDate + " 12:00:00")) {
                            /*
                            if(json.data.result[index]['playing'])
                                list.am.unshift(json.data.result[index]);
                            else*/
                            list.am.push(json.data.result[index]);
                        } else {
                            /*
                            if(json.data.result[index]['playing'])
                                list.pm.unshift(json.data.result[index]);
                            else*/
                            list.pm.push(json.data.result[index]);
                        }
                    });

                    obj.openDlg($container, '预览', 1180, 820);
                    var $tmpl = $("#operate-preview");


                    $.each(alternatePlayCollection, function(index, element) {

                        alternatePlayCollection[index]['contentType'] = Channel.Config.programTypeData[element.contentType];
                        if (!element.duration)
                            alternatePlayCollection[index]['duration'] = '0时0分0秒';
                        else
                            var theTime = parseInt(element.duration / 1000); // 秒
                        var theTime1 = 0; // 分
                        var theTime2 = 0; // 小时
                        if (theTime > 60) {
                            theTime1 = parseInt(theTime / 60);
                            theTime = parseInt(theTime % 60);
                            if (theTime1 > 60) {
                                theTime2 = parseInt(theTime1 / 60);
                                theTime1 = parseInt(theTime1 % 60);
                            }
                        }
                        var result = "" + parseInt(theTime) + "秒";
                        if (theTime1 > 0) {
                            result = "" + parseInt(theTime1) + "分" + result;
                        }
                        if (theTime2 > 0) {
                            result = "" + parseInt(theTime2) + "小时" + result;
                        }

                        alternatePlayCollection[index]['duration'] = result;

                    });

                    $container.html($tmpl.tmpl({
                        list: list,
                        backup: alternatePlayCollection,
                        date: currentDateStr
                    }));


                    if (new Date() < new Date(currentDate + " 12:00:00")) {
                        $('.nav-tabs a:first').tab('show');
                        self._scrollProgramList($("#am"));
                        self._programListScrollEvent("#am");
                    } else {
                        $('.nav-tabs a:last').tab('show');
                        self._scrollProgramList($("#pm"));
                        self._programListScrollEvent("#pm");
                    }

                    // 获取预览流
                    Channel.Dao.getPreviewStream({
                        qipuId: qipuId
                    }, function(json) {
                        if (json.code == 'A00000') {
                            var flvPlayer = self._flvPlayer(json.data.flv);

                            $("#flv").html(flvPlayer);
                            $("#mp4").html("mp4加载失败!");
                        } else {
                            $("#flv").html("flv加载失败!");
                            $("#mp4").html("mp4加载失败!");
                        }


                    });


                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }


            });
        },

        // 滚动滚动条到当前播放位置
        _scrollProgramList: function(obj) {
            var offset = 0,
                top = 0;

            $.each(obj.find("table tr"), function(i, item) {
                var $this = $(item);
                offset += $(item).height();
                if ($this.attr('cur-program') == 'playing') {
                    return false;
                }

            });

            $divObj = obj.find("div");
            var height = $divObj.height();

            if (offset > height) {
                top = offset - height;
            }

            $divObj.scrollTop(top);
        },
        // 节目列表滚动事件
        _programListScrollEvent: function(slc) {
            var self = this;
            $("a[href=" + slc + "]").unbind("click").bind("click", function() {
                $(slc).addClass("active");
                self._scrollProgramList($(slc));
            });
        },
        // 预览备播库列表
        _carousel: function() {},

        // 获取类型写入config
        getType: function(options) {

            Channel.Dao.getType({
                type: options.type
            }, function(json) {

                if (json.code == 'A00000') {

                    var valField = 'val';

                    if (options.type == 'LiveType') {
                        var valField = 'descr';
                    }

                    $.each(json.data, function(i, n) {
                        if (n != undefined)
                            Channel.Config[options.cfgName][n.key] = n[valField];
                    });

                    if (typeof(options.requestLoaded) == 'function') {
                        options.requestLoaded();
                    }

                } else {
                    var msg = Stream.Config.REQUEST_FAIL;
                    if (json.msg != undefined)
                        msg = json.msg;

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }
            });

        },

        deleteChannel: function(id) {

            auth.getAuthData({
                tips: 1,
                url: '/epg/channel_delete.html'
            }, function(rt) {

                if (rt) {
                    $(document).tips({
                        content: '很抱歉，您没有删除的权限!',
                        type: "error"
                    });

                    return;
                }

                //if(!window.confirm('你确定要删除吗？'))
                //return;
                SystemDialog.queryConfirm("你确定要删除吗？", function(flag) {
                    if (flag === true) {

                        Channel.Dao.deleteChannelData({
                            id: id
                        }, function(json) {

                            if (json.code == 'A00000') {

                                var sg = Channel.Action.getChannelGrid({});
                                sg.query();

                            } else {

                                var msg = Stream.Config.REQUEST_FAIL;
                                if (json.msg != undefined)
                                    msg = json.msg;

                                $(document).tips({
                                    content: msg,
                                    type: "error"
                                });

                            }


                        });
                    }
                });

            });
        }
    });

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Stream.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
define(
    '../stream/Stream',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Stream = window.Stream || {
            version: '1.0'
        };


    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Stream.Action.js
 * @path:   js-src/Stream/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
define(
    '../stream/Stream.Action',['require','exports','module'],function(require, exports, module) {


        Stream.Action = (function() {

            // 表格
            var StreamGrid = null;



            var getStreamGrid = function(options) {

                if (!StreamGrid) {
                    StreamGrid = new Stream.Grid($.extend(true, {
                        '$container': $('#StreamListContainer'),
                        type: 0
                    }, options));
                }

                return StreamGrid;

            }

            var StreamGridRun = function(options) {

                StreamGrid = getStreamGrid(options);
                StreamGrid.run();

                console.log('grid run');

            }


            var run = function() {
                Ancestor.Config.EPG_AUTH.list = '/stream/list';
                StreamGridRun({});
                //Stream.Util.streamNameSuggest($('input.streamNameSuggest'));
            }

            return {

                run: run,
                getStreamGrid: getStreamGrid
            }

        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Channel.Config.js
 * @path:   js-src/Channel/
 * @desc:   Channel公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
///import js-src/lib/
///import js-src/com/
define('../stream/Stream.Config',['require','exports','module'],function(require, exports, module) {
    Stream.Config = $.extend({}, Ancestor.Config, {

        STREAM_FORM: {

            rules: {
                peerCount: {
                    required: true,
                    min: 1
                },


            },


            messages: {
                "peerCount": {
                    "required": "镜像服务器数不能为空",
                    "min": "镜像服务器数不能小于1"

                },
            }

        },

        // 修改前数据
        BEFORE_DATA: null,

        // 编码状态
        STATUS: {},

        // 码流清晰度
        TYPE: {},

        // 地区
        DEST: {},

        CUTTER_ID: {
            FLV: [],
            TS: []
        },

        TABLE_COLMODEL_CONFIG: {
            /*
                id: {                    name: 'id',
                    index:'id',
                    title: false,
                    width: 50,
                    align: 'center',
                    sortable: false
                },*/
            channelName: {
                name: 'channelName',
                index: 'channelName',
                title: false,
                width: 70,
                align: 'center',
                sortable: false
            },
            streamName: {
                name: 'streamName',
                index: 'streamName',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamName(v, r);
                }
            },

            streamIp: {
                name: 'streamIp',
                index: 'streamIp',
                width: 90,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamIp(v, r);
                }

            },

            encodedIp: {
                name: 'encodedIp',
                index: 'encodedIp',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.encodedIp(v, r);
                }
            },

            inputSignal: {
                name: 'inputSignal',
                index: 'encodedIp',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return Stream.Util.formatter.inputSignal(v, r);
                }
            },

            dolbySignal: {
              name: 'dolbySignal',
                index: 'dolbySignal',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.dolbySignal(v, r);
                }
            },

            dest: {
                name: 'dest',
                index: 'dest',
                width: 40,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.dest(v, r);
                }
            },

            streamType: {
                name: 'streamType',
                index: 'streamType',
                title: false,
                width: 60,
                sortable: false,
                align: 'center',
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamType(v, r);
                }

            },

            status: {
                name: 'status',
                index: 'status',
                title: false,
                width: 60,
                sortable: false,
                align: 'center',
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.status(v, r);
                }

            },

            bitRate: {
                name: 'bitRate',
                index: 'bitRate',
                title: false,
                width: 60,
                align: 'center',
                sortable: false
            },

            inputBits: {
                name: 'inputBits',
                index: 'inputBits',
                title: false,
                width: 75,
                align: 'center',
                sortable: false
            },


            outputBits: {
                name: 'outputBits',
                index: 'outputBits',
                title: false,
                width: 80,
                align: 'center',
                sortable: false
            },


            aspectRatio: {
                name: 'aspectRatio',
                index: 'aspectRatio',
                title: false,
                align: 'center',
                width: 75
            },

            frameRate: {
                name: 'frameRate',
                index: 'frameRate',
                title: false,
                align: 'center',
                width: 75
            },

            screenSize: {
                name: 'screenSize',
                index: 'screenSize',
                title: false,
                sortable: false,
                align: 'center',
                width: 75

            },
            encodeType: {
                name: 'encodeType',
                index: 'encodeType',
                title: false,
                width: 70,
                align: 'center',
                sortable: false,

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.encodeType(v, r);
                }
            },

            audio: {
                name: 'audio',
                index: 'audio',
                title: false,
                width: 70,
                align: 'center',
                sortable: false
            },

            peerCount: {
                name: 'peerCount',
                index: 'peerCount',
                width: 90,
                sortable: false,
                align: 'center',
                title: false
            },

            addTime: {
                name: 'addTime',
                index: 'addTime',
                width: 120,
                sortable: false,
                align: 'center',
                title: false
            },

            updateTime: {
                name: 'updateTime',
                index: 'updateTime',
                width: 120,
                sortable: false,
                align: 'center',
                title: false
            },
            isEnable: {
                name: 'isEnable',
                index: 'isEnable',
                width: 75,
                sortable: false,
                align: 'center',

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.isEnable(v, r);
                }
            },
            create: {
                name: 'create',
                width: 150,
                sortable: false,
                title: false,
                align: 'center',

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.create(v, r);
                }

            },
            operate: {
                name: 'operate',
                width: 80,
                sortable: false,
                title: false,
                align: 'center',

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.operate(v, r);
                }

            }

        },


        TABLE: { //素材库查询列表配置
            url: '/api/stream/list',

            loadBeforeSend: function(xhr, settings) {
                var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },

            //datatype:"jsonp",
            multiselect: false,
            colNames: ["频道名称", "流名称", "RTMP地址", "编码器地址", "信号源", "杜比信号源", "地区", "清晰度", "编码状态",
                "码流", "推流流速率", "下载流速率", "画面比例", "帧率",
                "画面尺寸", "视频类型", "音频类型", "镜像服务器数", "添加时间", "最后更新时间", "上下线状态", "创建", "操作"
            ],

            colModel: ['channelName', 'streamName', 'streamIp', 'encodedIp', 'inputSignal','dolbySignal', 'dest', 'streamType', 'status',
                'bitRate', 'inputBits', 'outputBits', 'aspectRatio', 'frameRate', 'screenSize', 'encodeType', 'audio',
                'peerCount', 'addTime', 'updateTime', 'isEnable', 'create', 'operate'
            ]
        },

        // 全景直播类型
        VIDEO_TYPE: {},

        // 3D直播参数
        THREE_D_VIDEO_TYPE: {
            "1": "普通视频",
            "2": "偏振(左右)3D格式",
            "3": "红蓝3D格式",
            "4": "上下3D格式",
        },

        // 流列表信息
        STREAMS_INFO: {},

        // 频道信息
        CHANNEL_INFO: null,

        // 流状态查询
        STREAM_SPAN: {
            "flv": 'http://cutteradmin.qiyi.domain:7777/statchannel?ch={channelName}&user=ppslive&src_type=PPC&version=2.0',
            "ts": 'http://cutteradmin.qiyi.domain:7777/statm3u8_ts?ch={channelName}&user=ppslive&src_type=PPC&version=2.0',
            "newts": 'http://cutteradmin.qiyi.domain:7777/stathttp2ts?ch={channelName}&user=ppslive&src_type=PPC&version=2.0',
            "dolby": 'http://cutteradmin.qiyi.domain:7777/stathttp2ts?ch={channelName}&user=ppslive&src_type=PPC&version=2.0'
        },

        STREAM_API_VERSION: {
            "0": '1.2',
            "1": '2.0'
        },

        // 码流信息(分辨率， 视频码率， 音频码率， 比例)
        STREAM_TYPE_INFO: {
            // stream_type, resolution, video_rate, audio_rate, video_ratio
            "TOP_SPEED": ['200p', '640x360', '200k', '32', '16:9'],
            "SMOOTH": ['360p', '640x360', '400k', '48', '16:9'],
            "HIGH_DEFINITION": ['540p', '960x540', '800k', '64', '16:9'],
            "RESOLUTION_720P": ['720p', '1280x720', '1.2m', '64', '16:9'],
            "RESOLUTION_1080P": ['1080p', '1920x1080', '2.0m', '128', '16:9'],
            "RESOLUTION_2K": ['2K', '2560x1440', '5.0m', '256', '16:9'],
            "RESOLUTION_4K": ['4K', '3840x2160', '6.0m', '256', '16:9']
        },

        ENCODER_CONFIG: (function() {
            var prefix = auth.dev() ? 'http://10.77.44.136:50001/dispatch/' : 'http://lunbodisp.live.qiyi.domain/dispatch/';
            return {
                encoder_close: prefix + "close",
                encoder_state: prefix + "state",
                encoder_start: prefix + "start",
                liveType_lb: '3'
            }
        })(),
        VRS_DATA:null,

        CUTTERINFO_URL: {
            'FLV': 'http://cutteradmin.qiyi.domain:7777/channelusage?user=ppscroot',
            'TS': 'http://cutteradmin.qiyi.domain:7777/m3u8_tsusage?user=ppscroot',
        },
        VRS_CONFIG:{
            S_SRC_13:"03032001010000000000",
            S_SRC_15:"02020031010000000000",
            BASE_FREE_URL:"http://live.video.iqiyi.com/live?k_uidgtzzvy7f4defxriu2jiqcclojibbczdj",
            BASE_VIP_URL:"http://port.qiyi.com/live/vip/ts"
        }

        //        ENCODER_CONFIG: {
        //
        //          encoder_start : 'http://10.23.70.35:50001/dispatch/start?channelid=${channelid}&encoder=abcd&obj=rtmp://10.121.86.127/live/xiang&progid=375544100',
        //          encoder_close : auth.dev() ? 'http://10.23.70.35:50001/dispatch/close' : 'http://lunbodisp.live.qiyi.domain/dispatch/close',
        //          encoder_state : auth.dev() ? 'http://10.23.70.35:50001/dispatch/state' : 'http://lunbodisp.live.qiyi.domain/dispatch/state',
        //          encoder_start : auth.dev() ? 'http://10.23.70.35:50001/dispatch/start' : 'http://lunbodisp.live.qiyi.domain/dispatch/start',
        //          liveType_lb : '3',
        //      }

    });
});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Stream.Dao.js
 * @path:   js-src/Stream/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-07
 */
define(
    '../stream/Stream.Dao',['require','exports','module'],function (require, exports, module) {

        Stream.Dao = $.extend({}, Ancestor.Dao, {

            // 直播流添加
            addStreamData: function (data, callback) {
                var options = {
                    url: '/api/stream/create',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/create');
            },

            // 直播流修改
            modifyStreamData: function (data, callback) {
                var options = {
                    url: '/api/stream/edit',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/edit');
            },


            // 直播流删除
            delStreamData: function (data, callback) {
                var options = {
                    url: '/api/stream/deleteById',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/deleteById');
            },

            // 获取直播流数据列表
            getStreamData: function (data, callback) {
                var options = {
                    url: '/api/stream/list',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/list');

            },

            // 获取创建直播流数信息
            getStreamInfo: function (data, callback) {
                var options = {
                    url: '/api/liveStream/getList',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/liveStream/getList');
            },


            // 流名称关联频道
            bindStreamName: function (data, callback) {
                var options = {
                    url: '/api/stream/binding',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/binding');
            },

            // 流信息操作
            streamInfoOperate: function (data, callback) {
                var options = {
                    url: '/api/' + data.api,
                    dataType: 'json',
                    data: data.data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/' + data.api);
            },

            getStreamNameCodeData: function (url, data, callback) {

                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, url.split('api')[1]);
            },

            // 调用第三方接口创建轮播台流
            encoderOperation: function (data, callback) {
                $.ajax({
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    beforeSend: function (request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                });
            },

            getCurrentProgram: function (data, callback) {
                var options = {
                    url: '/api/program/list',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/list');
            },

            // 保存全景直播参数
            addVideoTypeData: function (data, callback) {
                var options = {
                    url: '/api/channel/setPanoFormat',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/setPanoFormat');
            },

            // 保存3D直播参数
            saveThreeD: function (data, callback) {
                var options = {
                    url: '/api/channel/setThreeD',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/channel/setThreeD');
            },


            getCutterIdInfo: function (data, callback) {
                var options = {
                    url: '/api/stream/cutterIdInfo',
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data)
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/cutterIdInfo');
            },

            getCutterIdInfoNew: function (data, callback) {
                $.ajax({
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    beforeSend: function (request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                });
            },

            switchBackup: function (data, callback) {
                var options = {
                    url: '/api/stream/switchBackup',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data)
                    }
                };

                Ancestor.Dao.ajax(options, '/stream/switchBackup');
            },
            //获取频道数据
            getChannelData:function(data,callback){
                var self =this;
                var options = {
                    url: '/api/channel/list',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, '/channel/list');
            }

        });
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Stream.Base.js
 * @path:   js-src/Stream/
 * @desc:   Stream模块下基础业对象类
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
define(
    '../stream/Stream.Grid',['require','exports','module'],function (require, exports, module) {


        Stream.Grid = function (options) {
            this.dao = Stream.Dao;
            this.id = Ancestor.Util.getUrlId('id');
            this.qipuId = Ancestor.Util.getUrlId('qipuId');
            //    this.name = decodeURI(Ancestor.Util.getUrlId('name'));
            this.name = decodeURIComponent(Ancestor.Util.getUrlId('name'));
            this.config = Stream.Config;
            this.dlg = $("#stream-operate-dlg");
            this.videoTypeDlg = $("#video-type-operate-dlg");
            this.threeDDlg = $("#three-d-operate-dlg");
            this.streamsPreviewDlg = $("#streams-preview-dlg");
            this.options = options || {};
        };

        Com.inherits(Stream.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
                self.initConfigOfType({
                    'sn': 'RtmpLocation',
                    'sk': 'DEST'
                }); // 地区
                self.initConfigOfType({
                    'sn': 'video_type',
                    'sk': 'VIDEO_TYPE'
                }); // 全景直播
                self.initCutterIdInfoNew("FLV");
                self.initCutterIdInfoNew("TS");
                $("#title").text(self.name);
            },

            initConfigOfType: function (options) {

                Ancestor.Dao.getType({
                    type: options.sn
                }, function (json) {
                    if (json.code == 'A00000') {
                        var config = Stream.Config[options.sk];
                        if (options.sn == 'RtmpLocation') {
                            config[''] = '';
                        }

                        $.each(json.data, function () {
                            if (options.sn == 'StreamType' || options.sn == 'RtmpLocation')
                                config[this.val] = this.descr;
                            else
                                config[this.key] = this.descr;
                        });

                    } else {
                        console.log('fail!');
                    }

                    if (typeof(options.requestLoaded) == 'function') {
                        options.requestLoaded();
                    }

                });

                //Channel.Dao.getSingleChannelData({'id':Ancestor.Util.getUrlId('id')},function(json) {
                //  if (json != 'undefined' && json.code == 'A00000') {
                //      // TODO delete after test
                //      json.data.pageUrl = 'http://www.iqiyi.com/c_19rron6ph6.html';
                //
                //      Stream.Config.CHANNEL_INFO = json.data;
                //  }
                //});

            },

            initCutterIdInfo: function (cutterType) {
                self.cutterType = cutterType;
                if (cutterType !== "FLV" && cutterType !== "TS") {
                    console.log("cutterType " + cutterType + " is not correct.");
                    return;
                }

                Stream.Dao.getCutterIdInfo({maxVal: 20, cutterType: cutterType}, function (json) {
                    if (json.code == 'A00000') {
                        var config = Stream.Config.CUTTER_ID[cutterType];

                        var cutterIdVal, descVal, countVal;

                        $.each(json.data, function () {
                            cutterIdVal = parseInt(this.cutterId);
                            descVal = this.desc;
                            countVal = this.count;

                            config.push({
                                cutterIdVal: cutterIdVal,
                                desc: descVal,
                                count: 20 - parseInt(countVal)
                            })
                        });
                    } else {
                        console.log('init CutterIdInfo failed!')
                    }
                })
            },

            initCutterIdInfoNew: function (cutterType) {
                self.cutterType = cutterType;
                if (cutterType !== "FLV" && cutterType !== "TS") {
                    console.log("cutterType " + cutterType + " is not correct.");
                    return;
                }

                var request = {};
                request.url = Stream.Config.CUTTERINFO_URL[cutterType];
                request.type = 'get';

                request.params = {};
                request = JSON.stringify(request);

                Stream.Dao.getCutterIdInfoNew({request: request}, function (json) {
                    if (json.status == '1') {
                        var config = Stream.Config.CUTTER_ID[cutterType];

                        var cutterIdVal, descVal, countVal;
                        var goodList = ['c12', 'c13', 'c15', 'c17', 'c18', 'c19', 'c20', 'c21', 'c22', 'c23', 'c24', 'c25', 'c26', 'c27', 'c28', 'c29'];

                        for (var key in json.data.remain) {
                            cutterIdVal = parseInt(key.slice(1));
                            descVal = key;
                            countVal = parseInt(json.data.remain[key]);

                            if (countVal !== 0) {
                                config.push({
                                    cutterIdVal: cutterIdVal,
                                    desc: descVal,
                                    count: countVal,
                                    good: $.inArray(descVal, goodList)
                                })
                            }
                        }
                        ;
                        config.sort(function (a, b) {
                            return b.count - a.count
                        });
                    } else {
                        console.log('init CutterIdInfo failed!')
                    }
                });

            },


            run: function () {
                var self = this;
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.initConfigOfType({
                            'sn': 'StreamType',
                            'sk': 'TYPE',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                }); // 流清晰度
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.initConfigOfType({
                            'sn': 'StreamStatus',
                            'sk': 'STATUS',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });

                //
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.dao.getChannelData({qipuId: self.qipuId}, function (data) {
                            if (data != null && data.code == 'A00000') {
                                self.config.CHANNEL_INFO = data.data.result[0];
                                console.log("Stream.Config.CHANNEL_INFO " + Stream.Config.CHANNEL_INFO.status);
                                Stream.Util.doVRSQuery(function () {
                                    ajaxBasicRequestLen();
                                })
                            } else {
                                console.log("vrs 接口访问失败");
                                ajaxBasicRequestLen();
                            }
                        })
                    }
                })

                self.ajaxBasicRequestManage.init(self, function (obj) {
                    obj.start();
                });
            },

            start: function (options, callback) {

                var self = this,
                    gridConfig = self.getGridConfig();

                self.init();

                self.echoQuery();
                options = $.extend(true, {
                    // width: 1500,
                    shrinkToFit: false
                    // autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
            },

            initGrid: function (options, callback) {
                var self = this;

                var gridConfig = self.getGridConfig();

                var $gridContainer = self.options.$container;

                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                    postData: {
                        fatherId: self.id
                    },
                    multiselect: true,
                    multiselectWidth: 30

                }, gridConfig, options);


                $grid.jqGrid('scroll', {});
                $grid.jqGrid(options);

                var params = $grid.jqGrid("getGridParam");
                params.rowNum = 500;
                params.pages = 1;

                if (Ancestor.Util.getUrlId('livetype') != Stream.Config.ENCODER_CONFIG.liveType_lb) {
                    $grid.hideCol("dest");
                }

            },

            query: function () {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                Stream.Config.TABLE.jsonReader = {

                    root: "data",

                    page: "pageNo",

                    total: "totalPages",

                    records: "totalCount"

                };

                $grid.jqGrid('setGridParam', {
                    postData: {
                        fatherId: self.id
                    }
                }).trigger('reloadGrid', [
                    {
                        page: 1
                    }
                ]);

            },

            getParam: function () {
                var self = this;
                var params = {};
                params.id = self.id;

                return params;

            },

            bindEvent: function () {
                var self = this;
                self.bindBasicEvent();
            },


            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;


                // 添加码流
                $container.find('.add-stream').click(function () {
                    self.addStreamShow({
                        title: '添加码流',
                        callback: "onAddStream"
                    });

                    var id = self.id,
                        name = self.name,
                        liveType = Ancestor.Util.getUrlId('livetype'),
                        universalCode = Ancestor.Util.getUrlId('universalcode'),
                        carouselDefaultStream = 'HIGH_DEFINITION',
                        playType = Stream.Config.CHANNEL_INFO.type == 6 ? 1 : 0;
                    $tmpl = $("#add-stream");

                    self.dlg.html($tmpl.tmpl({
                        channelName: name,
                        fatherId: id,
                        operate: 'add',
                        liveType: liveType,
                        universalCode: universalCode,
                        streamType: Stream.Config.TYPE,
                        cutterIdsFlv: Stream.Config.CUTTER_ID.FLV,
                        cutterIdsTs: Stream.Config.CUTTER_ID.TS,
                        cutterIdFlv: '0',
                        cutterIdTs: '0',
                        dest: Stream.Config.DEST,
                        carouselDefaultStream: carouselDefaultStream,
                        playType: playType
                    }));
                    Stream.Util.streamNameSuggest($('input.streamNameSuggest'));
                    Stream.Util.dolbyStreamNameSuggest($('input.dolbyStreamNameSuggest'));
                    Stream.Util.encodeTypeSwitch($('#stream-operate-dlg'))
                });

                // 全景直播参数
                $container.find('.add-video-type').click(function () {

                    var id = self.id,
                        $tmpl = $("#add-video-type"),
                        videoTypeInfo = {
                            'videoType': 1,
                            'angleX': 0,
                            'angleY': 0,
                            'zoomRate': '1.0'
                        };

                    Channel.Dao.getSingleChannelData({
                        'id': self.id
                    }, function (json) {
                        if (json.code == 'A00000' && typeof(json.data.panoFormat) != 'undefined') {
                            videoTypeInfo = JSON.parse(json.data.panoFormat);
                            videoTypeInfo.zoomRate = videoTypeInfo.zoomRate.toFixed(1);
                        }

                        self.addVideoTypeShow({
                            title: '全景直播参数',
                            callback: "onAddVideoType"
                        });
                        self.videoTypeDlg.html($tmpl.tmpl({
                            fatherId: id,
                            videoType: Stream.Config.VIDEO_TYPE,
                            videoTypeValue: videoTypeInfo['videoType'],
                            angleX: videoTypeInfo['angleX'],
                            angleY: videoTypeInfo['angleY'],
                            zoomRate: videoTypeInfo['zoomRate']
                        }));
                    });
                });

                // 3D直播参数
                $container.find('.three-d').click(function () {

                    var id = self.id,
                        $tmpl = $("#three-d"),
                        videoTypeInfo = {
                            'videoType': 1
                        };

                    Channel.Dao.getSingleChannelData({
                        'id': self.id
                    }, function (json) {
                        if (json.code == 'A00000' && typeof(json.data.threeD) != 'undefined') {
                            videoTypeInfo = JSON.parse(json.data.threeD);
                        }

                        self.saveThreeDShow({
                            title: '3D直播参数',
                            callback: "onSaveThreeD"
                        });
                        self.threeDDlg.html($tmpl.tmpl({
                            fatherId: id,
                            videoType: Stream.Config.THREE_D_VIDEO_TYPE,
                            videoTypeValue: videoTypeInfo['videoType']
                        }));
                    });
                });


                // 编码流预览
                $container.find('.streams-preview').click(function () {


                    Stream.Dao.getStreamInfo({
                        'fatherId': self.id,
                        'formatType': 'flv'
                    }, function (json) {
                        if (json.code == 'A00000' && json.data.length > 0) {
                            var $grid = self.$grid;
                            var datas = $grid.jqGrid('getData');
                            var result = {};
                            $.each(datas, function (i, element) {
                                result[element.streamName] = element;
                            });

                            Stream.Config.STREAMS_INFO = result;

                            var videoDatas = {};

                            $.each(json.data, function (i, data) {
                                var sn = data.streamName;
                                videoDatas[sn] = {};
                                videoDatas[sn].flv = data.url;
                                videoDatas[sn].rtmp = 'rtmp://' + result[sn].internalIp + '/live/' + sn;
                                videoDatas[sn].rtmpIp = result[sn].streamIp;
                                videoDatas[sn].streamType = Stream.Config.TYPE[result[sn].streamType];
                                if (result[sn].hasOwnProperty('inputSignal') && result[sn].inputSignal != "") {
                                    videoDatas[sn].inputSignal = result[sn].inputSignal;
                                    if (videoDatas[sn].inputSignal.split(':')[0] === 'rtmp') {
                                        videoDatas[sn].inputSignalType = 'rtmp'
                                    } else {
                                        videoDatas[sn].inputSignalType = 'else'
                                    }
                                } else {
                                    videoDatas[sn].inputSignal = '没有信号源信息'
                                    videoDatas[sn].inputSignalType = 'empty'
                                }

                            });

                            self.parsePlayer.call(self, videoDatas);

                        } else if (json.code == 'A00000' && json.data.length == 0) {
                            $(document).tips({
                                content: "没有正在编码中的流，无法预览!",
                                type: "error"
                            });
                        } else {
                            var msg = "获取流信息错误!";
                            if (json.msg != undefined)
                                msg = json.msg;

                            $(document).tips({
                                content: msg,
                                type: "error"
                            });
                        }


                    });

                });

                $container.find('.switch-backup').click(function () {
                    //$('.switch-backup').prop("disabled", "disabled");
                    $(document).tips({
                        content: "切换灾备中",
                        type: "loading"
                    });
                    Stream.Dao.switchBackup({
                        'fatherId': self.id,
                        'qipuId': self.qipuId
                    }, function (json) {
                        if (typeof(json) != 'undefined') {
                            if (json.code == 'A00000') {
                                $(document).tips({content: json.msg, type: "success"});
                                // 刷新页面
                                setTimeout("location.reload()", 1000);
                            } else if (json.data == "-1") {
                                $(document).tips({content: "切流失败，必须同一清晰度只有两条且编码中，一条上线一条下线", type: "error"});
                            } else {
                                $(document).tips({content: "操作失败", type: "error"});
                            }
                        } else {
                            $(document).tips({content: "操作失败", type: "error"});
                        }

                        //$('.switch-backup').removeAttr("disabled");

                    })
                });
            },

            parsePlayer: function (videoDatas) {
                var self = this;
                var id = self.id,
                    $tmpl = $("#streams-preview");

                var tvId = '0';
                var cId = '0';
                var pageUrl = Stream.Config.CHANNEL_INFO.pageUrl;
                var request = {};
                request.fatherId = self.id;

                request.startDate = Com.date.format(new Date(), "yyyy-MM-dd 00:00:00");
                request.endDate = Com.date.format(new Date(), "yyyy-MM-dd hh:mm:ss");

                Stream.Dao.getCurrentProgram(request, function (json) {
                    if (json.code == 'A00000' && json.data.result.length > 0) {
                        var result = json.data.result;
                        var program = result[result.length - 1];
                        //pageUrl = program.pageUrl.split('?')[0];
                        tvId = program.qipuId;
                        cId = Stream.Config.CHANNEL_INFO.qipuId;

                    }

                    self.addStreamsPreviewShow({
                        title: '编码流预览'
                    });
                    self.streamsPreviewDlg.html($tmpl.tmpl({
                        vDatas: videoDatas,
                        tvId: tvId,
                        channelId: cId,
                        pageUrl: pageUrl
                    }));
                });


            },

            flvPlayer: function (src) {
                return '<embed width="100%" height="300"' +
                    ' src="http://www.iqiyi.com/common/flashplayer/20141218/LivePlayer_3_0_3_4.swf" ' +
                    'quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
                    ' align="middle"' +
                    ' play="true"' +
                    ' loop="true"' +
                    ' scale="showall"' +
                    ' wmode="window"' +
                    ' devicefont="false"' +
                    ' bgcolor="#000000"' +
                    ' name="player"' +
                    ' menu="true"' +
                    ' allowfullscreen="true"' +
                    ' allowscriptaccess="always"' +
                    ' flashvars="vid=' + src + '&source=live.lego.iqiyi.com&cid=qc_100001_300089"' +
                    ' salign="" ' +
                    'type="application/x-shockwave-flash">';
            },

            rtmpPlayer: function (src) {
                return '<embed src="swfs/StrobeMediaPlayback.swf" width="100%" height="300" id="StrobeMediaPlayback" quality="high" bgcolor="#000000"' +
                    'name="StrobeMediaPlayback" allowfullscreen="true" pluginspage="http://www.adobe.com/go/getflashplayer"' +
                    'flashvars="src=' + src + '&autoHideControlBar=true&streamType=live&autoPlay=false&verbose=true" type="application/x-shockwave-flash">';
            },

            // 添加流
            addStreamShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#stream-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 600,
                    //height:320,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });

            },

            // 添加全景直播参数
            addVideoTypeShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#video-type-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 400,
                    height: 280,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                $(document).tips({
                                    content: "页面提交中",
                                    type: "loading"
                                });

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },


            // 添加3D直播参数
            saveThreeDShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#three-d-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 400,
                    height: 280,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                $(document).tips({
                                    content: "页面提交中",
                                    type: "loading"
                                });

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },

            // 添加编码流预览
            addStreamsPreviewShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#streams-preview-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 1200,
                    height: 900,
                    //maxHeight: 320,
                    position: ['center', 'center'],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },


            // 填加
            onAddStream: function (obj) {

                $(document).tips({
                    content: "页面提交中",
                    type: "loading"
                });

                var self = this;

                var $form = $(".stream-add-form"),
                    params = {};
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    key,
                    peerCount = null;

                var encodeType = $form.find("select[name=encodeType]").val();

                $.each($elements, function () {
                    name = this.name;
                    if (Ancestor.Util.getUrlId('livetype') == '3' && name == 'streamName' && $(this).val().split('_')[0] != 'lb') {
                        $(document).tips({
                            content: '流名称只能以"lb_"开头',
                            type: "error"
                        });

                        peerCount = 1;
                    }
                    if (name == 'peerCount' && $(this).val() > 157) {
                        $(document).tips({
                            content: '镜像服务器数不能大于157',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamIp' && $(this).val() == '' && encodeType == 0) {
                        $(document).tips({
                            content: '请填写RTMP IP',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamAddress' && $(this).val() == '' && encodeType == 1) {
                        $(document).tips({
                            content: '请填写流地址',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamIp' && $(this).val().split('.')[0] == 10) {
                        $(document).tips({
                            content: 'RTMP ip非外网ip,请填写外网ip',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'dest' && $(this).val() == '') {
                        $(document).tips({
                            content: '请选择一个地区',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'bcsNum') {
                        var bcsVal = $(this).val();
                        if (bcsVal > 10 || bcsVal < 3 || isNaN(bcsVal) || parseInt(bcsVal) + '' !== bcsVal) {
                            $(document).tips({
                                content: '广播源数填写错误',
                                type: "error"
                            });

                            peerCount = 1;
                        }
                    }

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $(this).val() || '';
                });

                if (peerCount)
                    return;

                Stream.Dao.addStreamData(params, function (json) {
                    if (json.code == 'A00000' || 'EPG00202' || 'EPG00203') {

                        self.query();

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            onSaveThreeD: function (obj) {
                var self = this;

                var $form = $(".three-d-form"),
                    params = {
                        channelId: self.id
                    };

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    count = null;
                $.each($elements, function () {
                    name = this.name;

                    params[name] = params[name] = $(this).val() || '';
                });

                if (count) return;

                Stream.Dao.saveThreeD(params, function (json) {
                    if (json.code == 'A00000') {

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });
            },

            onAddVideoType: function (obj) {

                var self = this;

                var $form = $(".video-type-add-form"),
                    params = {
                        channelId: self.id
                    };
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    count = null;
                $.each($elements, function () {
                    name = this.name;
                    if (name == 'angleX' && $(this).val() < 0) {
                        $(document).tips({
                            content: '默认视角X轴不能小于0',
                            type: "error"
                        });

                        count = 1;
                    }
                    if (name == 'angleY' && $(this).val() < 0) {
                        $(document).tips({
                            content: '默认视角Y轴不能小于0',
                            type: "error"
                        });
                        count = 1;
                    }
                    if (name == 'zoomRate' && $(this).val() <= 0) {
                        $(document).tips({
                            content: '默认缩放系数必须大于0',
                            type: "error"
                        });
                        count = 1;
                    }

                    params[name] = params[name] = $(this).val() || '';
                });

                if (count) return;

                Stream.Dao.addVideoTypeData(params, function (json) {
                    if (json.code == 'A00000') {

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            // 修改直播流前检查
            onModifyStreamCheck: function (data) {
                var beforeData = Stream.Config.BEFORE_DATA;
                var msg = "如需立即生效，请将该直播流的FLV和TS停止，删除，重新创建。";
                if (!beforeData || !beforeData.hasOwnProperty('bcsNum') || !beforeData.hasOwnProperty('cutterIdTs') || !beforeData.hasOwnProperty('cutterIdFlv') || !beforeData.hasOwnProperty('peerCount')) {
                    $(document).tips({
                        content: '发生异常，请重新修改',
                        type: "error"
                    });
                } else {
                    if (beforeData.bcsNum + '' !== data.bcsNum || beforeData.cutterIdFlv + '' !== data.cutterIdFlv ||
                        beforeData.cutterIdTs + '' !== data.cutterIdTs || beforeData.peerCount + '' !== data.peerCount) {

                        SystemDialog.queryAlert(msg);
                    }
                    return true;
                }

                return false;
            },

            // 修改直播流
            onModifyStream: function (obj) {


                var $form = $(".stream-add-form"),
                    params = {};

                // 提交前验证
                var validator = Channel.Util.getValidator($form, Stream.Config.STREAM_FORM);
                if (!validator.form())
                    return;


                $(document).tips({
                    content: "页面提交中",
                    type: "loading"
                });

                var self = this;


                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    key,
                    peerCount;

                $.each($elements, function () {
                    name = this.name;
                    if (name == 'peerCount' && $(this).val() > 157) {
                        $(document).tips({
                            content: '镜像服务器数不能大于157',
                            type: "error"
                        });

                        peerCount = 1;
                    }


                    if (name == 'bcsNum') {
                        var bcsVal = $(this).val();
                        if (bcsVal > 10 || bcsVal < 3 || isNaN(bcsVal) || parseInt(bcsVal) + '' !== bcsVal) {
                            $(document).tips({
                                content: '广播源数填写错误',
                                type: "error"
                            });

                            peerCount = 1;
                        }
                    }

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $(this).val() || '';
                });

                if (peerCount)
                    return;


                //if(!self.onModifyStreamCheck(params)){
                //    return;
                //}

                Stream.Dao.modifyStreamData(params, function (json) {
                    if (json.code == 'A00000' || 'EPG00204') {

                        self.query();

                        var html = '';
                        if (json.code == 'A00000') {
                            html = '修改成功';
                        } else {
                            html = json.msg;
                        }
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                        self.onModifyStreamCheck(params)

                    } else {

                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            // 删除
            onDelStream: function (obj) {
                var self = this;
                auth.getAuthData({
                    tips: 1,
                    url: '/epg/live_stream_delete.html'
                }, function (rt) {

                    if (rt) {
                        $(document).tips({
                            content: '很抱歉，您没有删除的权限!',
                            type: "error"
                        });

                        return;
                    }

                    //if(!window.confirm('你确定要删除吗？'))
                    //return;


                    SystemDialog.queryConfirm("你确定要删除吗？", function (flag) {
                        if (flag === true) {

                            $(document).tips({
                                content: "页面提交中",
                                type: "loading"
                            });

                            Stream.Dao.delStreamData(obj, function (json) {
                                if (json.code == 'A00000') {

                                    self.query();

                                    var html = '删除成功';
                                    $(document).tips({
                                        content: html,
                                        type: "success"
                                    });

                                } else {
                                    var msg = Stream.Config.REQUEST_FAIL;
                                    if (json.msg != undefined)
                                        msg = json.msg;

                                    $(document).tips({
                                        content: msg,
                                        type: "error"
                                    });


                                }

                            });
                        }
                    });
                });
            },


            playStream: function () {

                var self = this;
                var _options = self.options;
                var $container = _options.$container;
                $container.dialog({
                    title: '预览',
                    appendTo: _options.$form,
                    modal: true,
                    width: 800,
                    height: 600,
                    maxHeight: 600,
                    buttons: [
                        {
                            text: '确定',
                            click: function () {
                                self.onSelect();
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

                    },
                    close: function () {
                        self.onClose();
                    }
                });


            },


            streamInfo: function () {

                var self = this;
                var _options = self.options;
                var $container = _options.$container;
                $container.dialog({
                    title: '添加码流',
                    appendTo: _options.$form,
                    modal: true,
                    width: 800,
                    height: 600,
                    maxHeight: 600,
                    buttons: [
                        {
                            text: '确定',
                            click: function () {
                                self.onSelect();
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');


                    },
                    close: function () {
                        self.onClose();
                    }
                });


            },

            bindFormEvent: function ($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function (selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                    }

                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function (selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "maxDate", selectedDate);
                    }
                });
            }

        });

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Stream.Util.js
 * @path:   js-src/Stream/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
define('../stream/Stream.Util',['require','exports','module'],function (require, exports, module) {


    Stream.Util = $.extend(true, {}, Ancestor.Util, {

        // jqGrid 相关回调函数
        formatter: {

            streamName: function (v, r) {
                if (r.encodeType) {
                    //return '<a href="' + r.streamAddress + '" target="_blank">' + r.streamName + '</a>';
                    return '<a href="' + r.streamUrls + '" target="_blank">' + r.streamName + '</a>';
                } else {
                    //return '<a href="http://www.cutv.com/demo/live_test.swf?url=rtmp://' + r.streamIp + '/live/' + r.streamName + '" target="_blank">' + r.streamName + '</a>';
                    return '<a href="http://www.cutv.com/demo/live_test.swf?url=' + r.streamUrls + '" target="_blank">' + r.streamName + '</a>';
                }
            },

            streamIp: function (v, r) {
                var port = r.port || '8080';
                return '<a href="http://' + r.internalIp + ':' + port + '/stat" target="_blank">' + r.streamIp + '</a>';
            },

            encodedIp: function (v, r) {
                // return '<a href="http://' + r.encodedIp + '" target="_blank">' + r.encodedIp + '</a>';
                return '<a href="http://encoder.live.video.qiyi.domain/agent?ip=' + r.encodedIp + '" target="_blank">' + r.encodedIp + '</a>';
            },

            inputSignal: function (v, r) {
                var inputSignal = r.inputSignal;
                if (typeof inputSignal === 'undefined') {
                    return '';
                }

                if (inputSignal.split(':')[0] === 'rtmp') {
                    return '<a href="http://www.cutv.com/demo/live_test.swf?url=' + inputSignal + '" target="_blank">' + inputSignal + '</a>';
                } else {
                    return inputSignal;
                }
            },

            dolbySignal: function (v, r) {
                return '<a href="' + r.dolbyStreamUrls + '" target="_blank">' + r.dolbyStreamUrl + '</a>';
                //return r.dolbyStreamUrl;
            },

            dest: function (v, r) {
                return Stream.Config.DEST[r.dest];
            },

            status: function (v, r) {
                return Stream.Config.STATUS[r.status];
            },

            streamType: function (v, r) {
                return Stream.Config.TYPE[r.streamType];
            },

            isEnable: function (v, r) {
                return r.isEnable === '1' ? '上线' : '下线';
            },

            encodeType: function (v, r) {
                return r.encodeType == 0 ? 'H264' : 'H265';
            },

            create: function (v, r) {
                var optionsObj = {},
                    flvOptionsObj = {},
                    encoderOptionsObj = {};

                optionsObj.id = r.id;
                optionsObj.fatherId = r.fatherId;
                optionsObj.channelName = r.channelName;
                optionsObj.streamName = r.streamName;
                optionsObj.streamIp = r.streamIp;
                optionsObj.internalIp = r.internalIp;
                optionsObj.isDefault = 0;
                optionsObj.streamType = r.streamType;
                optionsObj.dolbyStreamName = r.dolbyStreamName;
                optionsObj.dolbyStreamUrl = r.dolbyStreamUrl;
                optionsObj.encodeType = r.encodeType;
                optionsObj.streamAddress = r.streamAddress;
                options = encodeURIComponent(JSON.stringify(optionsObj));

                flvOptionsObj = optionsObj;
                flvOptionsObj.isDefault = 1;
                flvOptions = encodeURIComponent(JSON.stringify(flvOptionsObj));

                encoderOptionsObj = optionsObj;
                encoderOptionsObj.dest = r.dest;
                encoderOptionsObj.destName = Stream.Config.DEST[r.dest];
                encoderOptionsObj.liveType = Ancestor.Util.getUrlId('livetype');
                encoderOptions = encodeURIComponent(JSON.stringify(encoderOptionsObj));

                var htmls = [];
                htmls.push('<div class="oper" data-id="">');
                if (encoderOptionsObj.liveType == Stream.Config.ENCODER_CONFIG.liveType_lb) {
                    htmls.push('<a href="javascript:;" data=' + encoderOptions + ' type="encoder" onclick="Stream.Util.saveStreamShow(this);">编码</a>');
                }

                // 0 = H264, 1 = H265
                if (r.encodeType == "1") {
                    htmls.push('<a href="javascript:;" data=' + options + ' type="newts" onclick="Stream.Util.saveStreamShow(this);">TS</a>');
                } else {
                    htmls.push('<a href="javascript:;" data=' + flvOptions + ' type="flv" onclick="Stream.Util.saveStreamShow(this);">FLV</a>');
                    htmls.push('<a href="javascript:;" data=' + options + ' type="ts" onclick="Stream.Util.saveStreamShow(this);">TS</a>');
                    if (r.dolbyStreamUrl != '') {
                        htmls.push('<a href="javascript:;" data=' + options + ' type="dolby" onclick="Stream.Util.saveStreamShow(this);">DOLBY</a>');
                    }
                }

                //htmls.push('<a href="javascript:;" data='+options+' type="p2p" onclick="Stream.Util.saveStreamShow(this);">P2P</a>');
                htmls.push('</div>');

                return htmls.join('');
            },

            operate: function (v, r) {

                var obj = {};
                obj.id = r.id;
                obj.fatherId = r.fatherId;
                obj.channelName = r.channelName;
                obj.streamName = r.streamName;
                obj.streamIp = r.streamIp;
                obj.streamType = r.streamType;
                obj.peerCount = r.peerCount;
                obj.bcsNum = r.bcsNum;
                obj.cutterIdFlv = r.cutterIdFlv;
                obj.cutterIdTs = r.cutterIdTs;
                obj.status = r.status;
                obj.isEnable = r.isEnable;
                obj.inputBits = r.inputBits;
                obj.outputBits = r.outputBits;
                obj.bitRate = r.bitRate;
                obj.aspectRatio = r.aspectRatio;
                obj.screenSize = r.screenSize;
                obj.liveType = Ancestor.Util.getUrlId('livetype');
                obj.dest = r.dest;
                obj.internalIp = r.internalIp;
                obj.streamApiVersion = r.streamApiVersion;
                obj.dolbyStreamName = r.dolbyStreamName;
                obj.dolbyStreamUrl = r.dolbyStreamUrl;
                obj.dolbyAudioChannel = r.dolbyAudioChannel;
                obj.encodeType = r.encodeType;
                obj.streamAddress = r.streamAddress;
                obj.playType = r.playType;

                var str = encodeURIComponent(JSON.stringify(obj));

                var htmls = [];
                htmls.push('<div class="oper" data-id="">');
                htmls.push('<a href="javascript:;" data=' + str + ' onclick="Stream.Util.modifyStream(this);">修改</a>');
                htmls.push('<a href="javascript:;" data=' + str + ' onclick="Stream.Util.deleteStream(this);">删除</a>');
                htmls.push('</div>');

                return htmls.join('');
            }
        },

        // 直播流事件绑定
        bindStreamEvent: function () {

        },

        // 保存流
        saveStreamShow: function (obj) {
            var options = JSON.parse(decodeURIComponent($(obj).attr('data')))
            options.type = $(obj).attr('type');

            var self = this;

            Stream.Dao.getStreamInfo({
                fatherId: options.fatherId,
                streamName: options.streamName
                //formatType : options.type
            }, function (json) {

                if (json.code == 'A00000') {

                    options.flv = null;
                    options.hcdn = null;
                    options.hcdnlive = null;
                    options.hasCreate = null;
                    options.status = null;

                    options.ts = null;
                    options.mp4 = null;
                    options.p2p = null;

                    options.dolby = null;
                    options.newts = null;

                    $.each(json.data, function () {

                        if (this.formatType == 'FLV') {
                            options.flv = this.url;
                            options.flvDelay = this.sliceDelay;
                            options.flvDelayS = this.delayS;
                            options.flvDelayE = this.delayE;

                            if (options.type == 'flv') {
                                options.status = this.status;
                                options.hasCreate = 1;
                                options.isDefault = this.isDefault;
                            }

                        }

                        if (this.formatType == 'HCDN') {
                            options.hcdn = this.url;
                            options.hcdnDelay = this.sliceDelay;
                            options.hcdnDelayS = this.delayS;
                            options.hcdnDelayE = this.delayE;
                        }

                        if (this.formatType == "HLFLV") {
                            options.hcdnlive = this.url;
                        }

                        if (this.formatType == 'TS') {
                            if (options.type == 'ts') {
                                options.ts = this.url;
                                options.tsUrl = Stream.Util.decodeVRSData(this.formatType, options.streamType);
                                options.status = this.status;
                                options.hasCreate = 1;
                            }

                            if (options.type == "newts") {
                                options.newts = this.url;
                                options.newtsCh = this.dolbyCh;
                                options.status = this.status;
                                options.hasCreate = 1;
                            }
                        }


                        if (this.formatType == 'MP4') {
                            options.mp4 = this.url;
                        }

                        if (this.formatType == 'P2P') {
                            options.p2p = this.url;
                            if (options.type == 'p2p') {
                                options.status = this.status;
                                options.hasCreate = 1;
                            }

                        }

                        if (this.formatType == 'DOLBY') {
                            options.dolby = this.url;
                            options.dolbyCh = this.dolbyCh;
                            if (options.type == 'dolby') {
                                options.status = this.status;
                                options.hasCreate = 1;
                            }
                        }

                    });

                    //options.liveStream = json.data;

                    //console.log(options);
                    if (options.type == 'encoder') {
                        var request = {};
                        request.url = Stream.Config.ENCODER_CONFIG.encoder_state;
                        request.type = 'get';

                        request.params = {
                            channelid: options.fatherId,
                            obj: 'rtmp://' + options.internalIp + '/live/' + options.streamName
                        };
                        request = JSON.stringify(request);

                        //$(document).tips({
                        //    content: "操作中...",
                        //    type: "loading"
                        //});

                        Stream.Dao.encoderOperation({
                            request: request
                        }, function (json) {
                            if (typeof(json) == "undefined") {
                                options.encoderState = "无法获取编码状态!";
                                options.status = 2;
                            } else if (json.error_code == '0') {
                                options.encoderState = "编码中...";
                                options.status = 0;
                            } else {
                                options.encoderState = "未编码";
                                options.status = 1;
                            }


                            $('.ui-tips-close').trigger('click');
                            self.fetchSpanInfos(options, obj);
                        });
                    } else {
                        self.fetchSpanInfos(options, obj);
                    }

                } else {
                    if (json.msg == undefined) {
                        msg = Stream.Config.REQUEST_FAIL;
                    } else {
                        msg = json.msg;
                    }

                    $(document).tips({
                        content: msg,
                        type: "error"
                    });
                }
            });

        },

        fetchSpanInfos: function (options, obj) {
            var self = this;
            var actionNext = function () {
                $(document).dequeue("fetchSpans");
            };

            var actions = [];

            if (options.type == 'flv') {
                actions.push(function () {
                    self.fetchSpanInfo(options, 'flv', actionNext)
                });
            } else if (options.type == 'ts') {
                actions.push(function () {
                    self.fetchSpanInfo(options, 'ts', actionNext)
                });
            } else if (options.type == 'newts') {
                actions.push(function () {
                    self.fetchSpanInfo(options, 'newts', actionNext)
                });
            } else if (options.type == 'dolby') {
                actions.push(function () {
                    self.fetchSpanInfo(options, 'dolby', actionNext);
                });
            }

            actions.push(function () {
                self.openStreamDlg(options, obj);
                actionNext()
            });

            $(document).queue("fetchSpans", actions);
            actionNext();

        },

        fetchSpanInfo: function (options, type, callback) {
            var self = this;
            var request = {};
            self.options = options;
            self.callback = callback;
            request.type = 'get';
            if (type == 'newts') {
                request.url = Stream.Config.STREAM_SPAN[type].replace("{channelName}", options['newtsCh']);
            } else if (type == 'dolby') {
                request.url = Stream.Config.STREAM_SPAN[type].replace("{channelName}", options['dolbyCh']);
            } else {
                request.url = Stream.Config.STREAM_SPAN[type].replace("{channelName}", options[type]);
            }
            request = JSON.stringify(request);

            Ancestor.Dao.redirectRequest({request: request}, function (json) {
                if (json.status == '1') {
                    var jsonData = json.data;
                    if (self.options.type == 'flv') {
                        self.options.flvSpan = jsonData.span;
                        self.options.streamServer = jsonData.stream_server;
                        self.options.streamIndex = jsonData.stream_server.trim().split("=")[1];
                        self.options.streamUrl = jsonData.stream_url.trim().split(" ");
                    } else if (self.options.type == 'ts') {
                        self.options.tsSpan = jsonData.span;
                        self.options.streamServer = jsonData.stream_server;
                        self.options.streamIndex = jsonData.stream_server.trim().split("=")[1];
                        self.options.streamUrl = jsonData.stream_url.trim().split(" ");
                    } else if (self.options.type == 'newts') {
                        self.options.newtsSpan = jsonData.span;
                    } else if (self.options.type == 'dolby') {
                        self.options.dolbySpan = jsonData.span;
                    }
                } else {
                    if (self.options.type == 'flv') {
                        self.options.flvSpan = -1;
                    } else if (self.options.type == 'ts') {
                        self.options.tsSpan = -1;
                    } else if (self.options.type == 'newts') {
                        self.options.newtsSpan = -1;
                    } else if (self.options.type == 'dolby') {
                        self.options.dolbySpan = -1;
                    }
                }
                self.callback();
            });
        },

        // 打开保存对话框
        openStreamDlg: function (options, a_tag) {
            var self = this;
            var $container = $("#stream-save-dlg");
            if (options.type != 'encoder') {
                var dlgTitle = '直播流创建';
            } else {
                var dlgTitle = '直播流编码';
            }

            $container.dialog({
                title: dlgTitle,
                appendTo: null,
                modal: true,
                width: 440,
                position: ['top', 'top+20'],

                open: function () {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

                },
                close: function () {

                }
            });

            var $tmpl = $("#save-stream");
            $container.html($tmpl.tmpl(options));

            if (options.type == "encoder") {
                self.bindEncoderBtn(a_tag);
            } else {
                self.bindStreamInfoBtn(a_tag);
            }
        },

        bindEncoderBtn: function (a_tag) {
            $(".btn-stream").unbind("click").bind('click', function () {

                $(this).attr('disabled', 'disabled');

                var type = $(this).attr('operate-type');
                var params = getParam($(".stream-info"));
                var self = $(this);

                var request = {};

                if (type == 'start') {
                    request.url = Stream.Config.ENCODER_CONFIG.encoder_start;

                    if (params.internalIp == '') {
                        $(document).tips({
                            content: "RTMP服务器IP填写错误, 无法找到内网地址",
                            type: "error"
                        });

                        self.removeAttr('disabled');
                        return;
                    }

                    request.params = {
                        channelid: params.fatherId,
                        encoder: 'null',
                        stream_type: Stream.Config.STREAM_TYPE_INFO[params.streamType][0],
                        //obj: 'rtmp://' + params.streamIp + '/live/' + params.streamName,
                        obj: 'rtmp://' + params.internalIp + '/live/' + params.streamName,
                        dest: params.dest
                    };

                    if (typeof(params.dest) == 'undefined' || params.dest == '') {
                        $(document).tips({
                            content: "未设置地区，无法启动流。",
                            type: "error"
                        });

                        self.removeAttr('disabled');

                        return;
                    }
                } else if (type == 'stop') {
                    request.url = Stream.Config.ENCODER_CONFIG.encoder_close;
                    request.params = {
                        channelid: params.fatherId,
                        obj: 'rtmp://' + params.internalIp + '/live/' + params.streamName
                    };
                } else {
                    $(document).tips({
                        content: "操作失败...",
                        type: "error"
                    });

                    self.removeAttr('disabled');
                    return;
                }

                request.type = 'get';
                request = JSON.stringify(request);

                //$(document).tips({
                //    content: "操作中...",
                //    type: "loading"
                //});

                Stream.Dao.encoderOperation({
                    request: request
                }, function (json) {
                    if (typeof(json) != "undefined" && json.error_code == '0') {
                        $('.ui-tips-close').trigger('click');

                        $("#stream-save-dlg").dialog('close');
                        $(a_tag).trigger("click");

                        $(document).tips({
                            content: "操作成功...",
                            type: "success"
                        });


                        // 刷新页面
                        setTimeout("location.reload()", 2000);

                    } else {
                        $(document).tips({
                            content: "操作失败...",
                            type: "error"
                        });

                        self.removeAttr('disabled');
                    }
                });
            });
        },

        bindStreamInfoBtn: function (a_tag) {
            $(".btn-stream").unbind("click").bind('click', function () {
                var type = $(this).attr('operate-type');
                var params = getParam($(".stream-info"));

                if (params.type == 'p2p') {
                    if (type == 'start')
                        type = 'online';
                    else
                        type = 'offline';
                }

                data = {};
                data.api = params.type + '/' + type;
                data.data = params;

                $(document).tips({
                    content: "页面提交中",
                    type: "loading"
                });

                Stream.Dao.streamInfoOperate(data, function (json) {

                    if (json.code == 'A00000') {
                        /*
                         $(document).tips({
                         content: "操作成功",
                         type: "close"
                         });
                         */

                        $('.ui-tips-close').trigger('click');

                        $("#stream-save-dlg").dialog('close');
                        $(a_tag).trigger("click");

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });

                    }

                });

            });
        },

        modifyStream: function (obj) {

            var self = this;
            var options = JSON.parse(decodeURIComponent($(obj).attr('data')));
            //console.log(options);
            var sg = Stream.Action.getStreamGrid();


            Stream.Dao.getStreamInfo({
                fatherId: options.fatherId,
                streamName: options.streamName
                //formatType : options.type
            }, function (json) {

                options.streamApiVersionEditable = true;
                if (json.code == 'A00000' && json.data.length > 0) {
                    options.streamApiVersionEditable = false;
                    options.streamApiVersionLabel = Stream.Config.STREAM_API_VERSION[options.streamApiVersion];
                }

                sg.addStreamShow({
                    title: '码流修改',
                    callback: "onModifyStream"
                });

                var $tmpl = $("#add-stream");
                options.streamTypeSlt = options.streamType;
                options.streamType = Stream.Config.TYPE;
                options.cutterIdsFlv = Stream.Config.CUTTER_ID.FLV;
                options.cutterIdsTs = Stream.Config.CUTTER_ID.TS;
                options.destVal = options.dest;
                options.dest = Stream.Config.DEST;
                options.operate = "modify";
                options.cutterIdFlv = options.cutterIdFlv + '';
                options.cutterIdTs = options.cutterIdTs + '';

                options.carouselDefaultStream = options.streamType;
                options.universalCode = Ancestor.Util.getUrlId('universalcode');

                Stream.Config.BEFORE_DATA = options;
                sg.dlg.html($tmpl.tmpl(options));

                self.setStreamTypeTip(options.streamTypeSlt);

                if (options.encodeType == 1) {
                    $("#streamIpDiv").hide();
                    $("#streamAddressDiv").show();
                } else {
                    $("#streamIpDiv").show();
                    $("#streamAddressDiv").hide();
                }
            });

        },

        deleteStream: function (obj) {

            var options = JSON.parse(decodeURIComponent($(obj).attr('data')));

            var tmp = {};

            tmp.id = options.id;
            tmp.fatherId = options.fatherId;
            tmp.streamName = options.streamName;

            if (options.status == 1) {
                $(document).tips({
                    content: tmp.streamName + '在编码中,请停止后再删除！',
                    type: "error"
                });
                return;
            }

            var sg = Stream.Action.getStreamGrid();

            sg.onDelStream(tmp);
        },


        streamNameCreateSuggest: function (el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function () {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function (i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function (event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function () {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function (request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function () {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;

                    var encodeType = $('#encodeType').val();
                    if (encodeType == "1") {
                        url = "/api/suggest/h265streamName"
                    } else {
                        url = "/api/suggest/streamName"
                    }

                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    param.fatherId = $(el).parents(".stream-add-form").find('[name="fatherId"]').val();

                    Stream.Dao.getStreamNameCodeData(url, param, function (json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                Stream.Util.highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function (event, ui) {
                    var content = ui.content;
                    $(this).autocomplete('validate', content);
                }).on('autocompleteselect', function (event, ui) {
                    ui.item.value = ui.item.streamName;
                    return $(this).autocomplete('setValue', ui.item);

                }).on('autocompletesearch', function (event, ui) {
                    //支持多选
                    return $(this).autocomplete('multiplesearch');
                });
        },

        streamName: function (el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width200">${streamName}</span>' +
                '<span style="border-right:none;">${streamIp}</span>' +
                '</div></div>';

            var title = {
                streamName: '流名称',
                streamIp: 'RTMP IP/流地址'
            };

            var getHtmlByData = function (data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            var suggestUrl = '/api/suggest/streamName';

            Stream.Util.streamNameCreateSuggest(el, $.extend(true, {

                url: suggestUrl,
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function (term) {
                    term = $.trim(term);
                    return {
                        'streamName': term
                    };
                },
                process: function (json) {
                    var encodeType = $('#encodeType').val();
                    if (json.data) {
                        var data = encodeType == "1" ? json.data : json.data.streamInfoList;

                        if (json.data.liveType == 1)
                            $('#streamIp').attr('disabled', 'disabled');

                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function (item) {
                            ret.push($.extend(true, item, {
                                streamName: encodeType == "1" ? Stream.Util.makeDolbyStreamName(item.outputSignal) : item.streamName,
                                streamIp: encodeType == "1" ? item.outputSignal : item.streamIp
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function (data, term) {
                    Stream.Util.highlight(data, 'dataName', term);
                },
                template: function (item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        },


        streamNameSuggest: function ($inputs, options) {

            $inputs.each(function (index, element) {
                var self = this;
                Stream.Util.streamName($(this), $.extend(true, {
                    validate: false,
                    select: function (e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.code);

                        var encodeType = $('#encodeType').val();
                        if (encodeType == 1) {
                            $('#streamAddress').val(data.item.streamIp);
                        } else {
                            $('#streamIp').val(data.item.streamIp);
                        }
                        //console.log(data);
                    },
                    onNoResult: function () {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function (event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        },


        dolbyStreamNameCreateSuggest: function (el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function () {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function (i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function (event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function () {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function (request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function () {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    param.fatherId = $(el).parents(".stream-add-form").find('[name="fatherId"]').val();
                    param.encodeType = $('#encodeType').val();

                    Stream.Dao.getStreamNameCodeData(url, param, function (json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                Stream.Util.highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function (event, ui) {
                    var content = ui.content;
                    $(this).autocomplete('validate', content);
                }).on('autocompleteselect', function (event, ui) {
                    ui.item.value = ui.item.dolbyStreamName;
                    return $(this).autocomplete('setValue', ui.item);

                }).on('autocompletesearch', function (event, ui) {
                    //支持多选
                    return $(this).autocomplete('multiplesearch');
                });
        },

        dolbyStreamName: function (el, options) {

            var tpl = '<div><div class="contract-item" style="width: 800px;">' +
                '<span class="contract-width200">${dolbyStreamName}</span>' +
                '<span style="border-right:none;">${dolbyStreamUrl}</span>' +
                '</div></div>';

            var title = {
                dolbyStreamName: '流名称',
                dolbyStreamUrl: '流地址'
            };

            var getHtmlByData = function (data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            Stream.Util.dolbyStreamNameCreateSuggest(el, $.extend(true, {

                url: '/api/suggest/dubistreamName',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function (term) {
                    term = $.trim(term);
                    return {
                        'streamName': term
                    };
                },
                process: function (json) {
                    if (json.data) {
                        var data = json.data;

                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function (item) {
                            ret.push($.extend(true, item, {
                                dolbyStreamName: Stream.Util.makeDolbyStreamName(item.outputSignal),
                                dolbyStreamUrl: item.outputSignal,
                                dolbyAudio: item.audio || ''
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function (data, term) {
                    Stream.Util.highlight(data, 'dataName', term);
                },
                template: function (item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        },

        makeDolbyStreamName: function (streamUrl) {
            var datas = streamUrl.split('/');
            return datas[datas.length - 1];
        },

        dolbyStreamNameSuggest: function ($inputs, options) {
            $inputs.each(function (index, element) {
                var self = this;
                Stream.Util.dolbyStreamName($(this), $.extend(true, {
                    validate: false,
                    select: function (e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.dolbyStreamName);
                        $('#dolbyStreamUrl').val(data.item.dolbyStreamUrl);
                        if (data.item.dolbyAudio == "copy") {
                            $('select[name=dolbyAudioChannel]').val("ATMOS");
                        } else {
                            $('select[name=dolbyAudioChannel]').val("5.1");
                        }
                        //console.log(data);
                    },
                    onNoResult: function () {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function (event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        },

        setStreamTypeTip: function (val) {
            var info = Stream.Config.STREAM_TYPE_INFO[val];

            $('#streamTypeTip').html('分辨率： ' + info[1] + ' 视频码率：' + info[2] + ' 音频码率：' + info[3]);
        },

        highlight: function (data, key, term) {
            data.forEach(function (item, i) {
                key = key || 'label';
                var label = item[key];
                if (!label || !term) {
                    return;
                }
                item[key] = (item[key] + '').replace(new RegExp('(' + term + ')', 'i'), '<b>$1</b>');
                // 高亮未输入部分
                // if (label.toLowerCase().indexOf(term.toLowerCase()) == 0) {
                //     item[key] = item[key].substr(0, term.length)
                //                   + '<b>'
                //                   + item[key].substr(term.length) + '</b>';
                // }
            });
        },
        decodeVRSData: function (formatType, streamType) {
            var vrsData = Stream.Config.VRS_DATA;
            var retValue = "";
            if (vrsData == null) {
                return retValue;
            }
            try {
                $.each(vrsData.streams, function (i, element) {
                    if (element.steamType == streamType.toUpperCase() && element.formatType == formatType.toUpperCase()) {
                        retValue = element.url;
                        return false;
                    }
                })
            } catch (e) {
                console.log("error", e);
            }
            return retValue;
        },

        encodeTypeSwitch: function ($container) {
            $container.find("select[name=encodeType]").bind("change", function (e) {
                var $curTarget = $(e.currentTarget);
                var streamIpDiv = $container.find("#streamIpDiv");
                var streamAddressDiv = $container.find("#streamAddressDiv");
                if ($curTarget.val() == 0) {
                    streamIpDiv.show();
                    streamAddressDiv.hide();
                } else if ($curTarget.val() == 1) {
                    streamIpDiv.hide();
                    streamAddressDiv.show();
                }
            });
            $container.find("select[name=encodeType]").change();
        },
        doVRSQuery: function (callback) {
            if (Stream.Config.CHANNEL_INFO != null) {
                var queryUrl = null;
                if (Stream.Config.CHANNEL_INFO.status == "FREE") {
                    Stream.Util.doVRSFreeQueryFirst(callback);
                } else {
                    Stream.Util.doVRSVipQuery(callback);
                }
            } else {
                callback()
            }
        },

        buildVRSFreeUrl: function (qipuId, platSrc) {
            var baseUrl = Stream.Config.VRS_CONFIG.BASE_FREE_URL;
            var params = [];
            params.push({key: "lc", value: "" + qipuId})
            params.push({key: "src", value: "" + platSrc})
            params.push({key: "v", value: "1"})
            params.push({key: "uid", value: "1351697526" })
            params.push({key: "t", value: "" + (Date.now() % 100) })
            params.push({key: "k_err_retries", value: "0" })
            params.push({key: "k_test", value: "1" })
            params.push({key: "k_ft1", value: "64" })
            $.each(params, function (i, entry) {
                baseUrl += "&" + entry.key + "=" + entry.value;
            })
            return baseUrl;
        },

        doVRSFreeQueryFirst: function (callback) {
            var queryUrl = Stream.Util.buildVRSFreeUrl(Stream.Config.CHANNEL_INFO.qipuId, Stream.Config.VRS_CONFIG.S_SRC_13);
            var options = {
                url: queryUrl,
                type: 'get',
                dataType: "json",
                timeout:2000,
                success: function (data) {
                    if (data == null || "A00000" != data.code) {
                        console.log("vrs 第一次请求失败:" + JSON.stringify(data));
                        Stream.Util.doVRSFreeQuerySecond(callback);
                    } else {
                        Stream.Config.VRS_DATA = data.data;
                        callback();
                    }
                },
                error: function (data) {
                    console.log("vrs 第一次请求失败")
                    Stream.Util.doVRSFreeQuerySecond(callback);
                }
            }
            EpgWeb.Dao.sendProxy(options)
        },
        doVRSFreeQuerySecond: function (callback) {
            var queryUrl = Stream.Util.buildVRSFreeUrl(Stream.Config.CHANNEL_INFO.qipuId, Stream.Config.VRS_CONFIG.S_SRC_15);
            var options = {
                url: queryUrl,
                type: 'get',
                dataType: 'json',
                timeout:2000,
                success: function (data) {
                    if (data == null || "A00000" != data.code) {
                        console.log("vrs 第二次请求失败:" + JSON.stringify(data))
                    } else {
                        Stream.Config.VRS_DATA = data.data;
                    }
                    callback();
                },
                error: function (data) {
                    console.log("vrs 第二次请求失败");
                    callback();
                }
            }
            EpgWeb.Dao.sendProxy(options)
        },
        buildVRSVipUrl: function (qipuId) {
            return Stream.Config.VRS_CONFIG.BASE_VIP_URL + "?lc=" + qipuId;
        },
        doVRSVipQuery: function (callback) {
            if (auth.dev()) {
                console.log(" disbale in dev mode ");
                callback();
                return ;
            }

            var getQueryUrl = Stream.Util.buildVRSVipUrl(Stream.Config.CHANNEL_INFO.qipuId);
            $.ajax(getQueryUrl, {
                timeout:2000,
                //      $.ajax("http://port.qiyi.com/live/vip/ts?lc=380309622",{
                success: function (data) {
                    if(typeof data == "string" && data.startsWith("http")){
                        console.log(" doVRSVipQuery suc:" + data);
                        Stream.Util.doVRSVipDataQuery(data.substring(0, data.lastIndexOf("&")), function () {
                            callback();
                        })
                    }else{
                        console.log("doVRSVipQuery fail:" +JSON.stringify(data) )
                        callback();
                    }
                },
                error: function (data) {
                    console.log("fail:" + data);
                    callback();
                }
            })
        },
        doVRSVipDataQuery: function (queryUrl, handler) {
            var options = {
                url: queryUrl,
                type: "get",
                dataType:"json",
                success: function (data) {
                    if (data != null && data.code == "A00000") {
                        Stream.Config.VRS_DATA = data.data;
                    } else {
                        console.log("doVRSVipDataQuery fail:" + JSON.stringify(data));
                    }
                    handler();
                },
                error: function (data) {
                    console.log("doVRSVipDataQuery fail:" + data);
                    handler();
                }
            }
            EpgWeb.Dao.sendProxy(options);
        }

    });

});
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 * 
 * @file:   StatisticOcr2.js
 * @path:   js-src/StatisticOcr/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
	'../statisticOcr/StatisticOcr2',['require','exports','module'],function(require, exports, module){
///import js-src/lib/
///import js-src/com/
window.StatisticOcr2 = window.StatisticOcr2 || { version : '1.0' };
        ///api/statistic/data/ocr/new
        StatisticOcr2.Constant = {
            baseApiUrl: "/api/",
            thirdUrl_query_user:"http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_type: "http://lego.iqiyi.com/suggest/operation",
            devMode: auth.dev()
        }

        StatisticOcr2.urlConfig = (function () {
            var useUrl = StatisticOcr2.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var sdGetUrl = useUrl + "sd";
            var createUrl = useUrl + "statistic/ocr/new";
            var newListUrl = useUrl + "statistic/ocr/list";
            var queryAvgAndFullPercentUrl = useUrl + "statistic/ocr/avgAndFullPercent";
            var getOcrExcelUrl = useUrl + "statistic/download/ocrExcel";
            var queryChannelName =(StatisticOcr2.Constant.devMode ? "http://10.23.70.33:7000" : "http://10.23.70.219")+"/v1/channel/fuzzyquery";
            return {
                sdGetUrl: sdGetUrl,
                createUrl:createUrl,
                newListUrl:newListUrl,
                queryAvgAndFullPercentUrl:queryAvgAndFullPercentUrl,
                redirectUrl:redirectUrl,
                getOcrExcelUrl:getOcrExcelUrl,
                queryChannelName:queryChannelName

            }
        })()
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticOcr2.Action.js
 * @path:   js-src/StatisticOcr/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
    '../statisticOcr/StatisticOcr2.Action',['require','exports','module'],function(require, exports, module) {

        StatisticOcr2.Action = (function() {

            //表格
            //统计OCR列表 old begin=====================
            var statisticOcrGrid = null;

            var getStatisticOcrGrid = function (options) {
                if (!statisticOcrGrid) {
                    statisticOcrGrid = new StatisticOcr2.Grid($.extend(true,
                    {'$grid': $('#list'), type:0}, options))
                }
                return statisticOcrGrid;
            }

            var statisticOcrGridRun = function(options) {
                statisticOcrGrid = getStatisticOcrGrid(options);
                statisticOcrGrid.init();
                console.log('grid run');
            }


            var run = function() {
                Ancestor.Config.EPG_AUTH.list='/statisticOcr/list';
                statisticOcrGridRun({});
            }
            //统计OCR列表 old over=====================
            return {
                run:run,
                getStatisticOcrGrid:getStatisticOcrGrid
            }
        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Config.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */

define('../statisticOcr/StatisticOcr2.Config',['require','exports','module'],function (require, exports, module) {
        StatisticOcr2.Config = $.extend({}, Ancestor.Config, {

            TABLE_COLMODEL_CONFIG: {
                id: {
                    name: 'id',
                    index: 'id',
                    title: false,
                    width: 80,
                    align: 'center',
                    hidden: true,
                    sortable: false
                },
                user: {
                    name: 'user',
                    index: 'user',
                    width: 100,
                    align: 'center',
                    sortable: false,
                    title: false
                },
                channelName: {
                    name: 'channelName',
                    index: 'channelName',
                    width: 100,
                    align: 'center',
                    title: false,
                    sortable: false
                },
                userTitle: {
                    name: 'userTitle',
                    index: 'userTitle',
                    title: false,
                    width: 200,
                    sortable: false,
                    align: 'center'
                },
                ocrTitle: {
                    name: 'ocrTitle',
                    index: 'ocrTitle',
                    title: false,
                    width: 200,
                    sortable: false,
                    align: 'center'
                },
                userTitleCharLen: {
                    name: 'userTitleCharLen',
                    index: 'userTitleCharLen',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return StatisticOcr2.Util.formatter.titleCharLen(v, o, r);
                    }
                },
                ocrTitleCharLen: {
                    name: 'ocrTitleCharLen',
                    index: 'ocrTitleCharLen',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return StatisticOcr2.Util.formatter.titleCharLen(v, o, r);
                    }
                },
                ocrFlag: {
                    name: 'ocrFlag',
                    index: 'ocrFlag',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticOcr2.Util.formatter.ocrFlag(v, o, r);
                    }
                },
                percent: {
                    name: 'percent',
                    index: 'percent',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticOcr2.Util.formatter.percent(v, o, r);
                    }
                },
                addTime: {
                    name: 'addTime',
                    index: 'addTime',
                    title: false,
                    sortable: false,
                    width: 80,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticOcr2.Util.formatter.addTime(v, o, r);
                    }
                },
                legoProgramId: {
                    name: 'legoProgramId',
                    index: 'legoProgramId',
                    title: false,
                    sortable: false,
                    width: 100,
                    align: 'center'
                },
                liveBeginTime: {
                    name: 'liveBeginTime',
                    index: 'liveBeginTime',
                    title: false,
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                liveEndTime: {
                    name: 'liveEndTime',
                    index: 'liveEndTime',
                    title: false,
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                operator_download: {
                    title: false,
                    sortable: false,
                    width: 70,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticOcr2.Util.formatter.operator_download(v, o, r);
                    }
                }
            },


            TABLE_OCR_NEW: {
                url: StatisticOcr2.urlConfig.newListUrl,
                multiselect: true,
                loadtext: '加载中...',
                loadui: 'block',
                rowNum: 20,
                loadBeforeSend: function (xhr, settings) {
                    var auth = Ancestor.Util.getAuth("/statistic/data/ocr/new");
                    xhr.setRequestHeader('Sign', auth.sign);
                    xhr.setRequestHeader("Time", auth.clientTime);
                    xhr.setRequestHeader("From", auth.from);
                    return true;
                },
                datatype: "json",
                height: 450,
                caption: "OCR统计列表",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                colNames: ["创建日期", "乐高节目ID","编辑输入标题", "OCR提示标题", "电视台", "制作人员", "是否使用\n智能拆条", "输入标题\n字数", "提示标题\n字数", "准确率", "直播开始时间", "直播结束时间", "样本下载"],
                colModel: ['addTime',"legoProgramId", 'userTitle', 'ocrTitle', 'channelName', 'user',
                    'ocrFlag', 'userTitleCharLen', 'ocrTitleCharLen', 'percent', 'liveBeginTime', 'liveEndTime', 'operator_download'],
                pager: "#pager",
                loadComplete: function () {
                    console.log(" loadComplete notify ");
                    $("#query_avg_loading").show();
                    $("#query_avg_over").hide();
                    if($("#list").data("data") != null && $("#list").data("data").code == "A00000"){
                        $("span[name=span_total_num]").html($("#list").data("data").data.totalCount);
                        StatisticOcr2.Util.doQueryAvgPercent();
                     //   $("#list").data("data")
                    }else{
                        $("#query_avg_loading").hide();
                    }
                },
                gridComplete: function () {
                    console.log(" gridComplete notify ");
                }
            }
        });
    }
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticOcr2.Dao.js
 * @path:   js-src/StatisticOcr/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
    '../statisticOcr/StatisticOcr2.Dao',['require','exports','module'],function (require, exports, module) {

        StatisticOcr2.Dao = $.extend({}, EpgWeb.Dao, {

            getAvgAndFullPercent: function (data, callback) {
                var options = {
                    url: StatisticOcr2.urlConfig.queryAvgAndFullPercentUrl,
                    type: "post",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                        console.log("getAvgAndFullPercent ");
                    },
                    error: function (data) {
                        callback.call(this, data);
                        console.log("error getAvgAndFullPercent");
                    }
                }
                Ancestor.Dao.ajax(options, "/statistic/ocr/avgAndFullPercent");
            }
        });
    }
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticOcr2.Base.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr模块下基础业对象类
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
    '../statisticOcr/StatisticOcr2.Grid',['require','exports','module'],function (require, exports, module) {

        StatisticOcr2.Grid = function (options) {
            this.dao = StatisticOcr2.Dao;
            this.config = StatisticOcr2.Config;
            this.options = options || {};
        };

        Com.inherits(StatisticOcr2.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.bindEvent();
                self.initSuggest();
                self.initGrid();
            },
            initGrid: function (options, callback) {
                var self = this;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_OCR_NEW);
                //params.rowNum=10;
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            initSuggest: function () {
            //    var self = this;
                var fuzzyQuerySuggest = {
                    options: {
                        source: StatisticOcr2.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticOcr2.urlConfig.queryChannelName, type: "get", params: {keyword: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }

                $("input[name=channelName]").suggest(fuzzyQuerySuggest.options)

                var emailSuggest = {
                    options: {
                        source: StatisticOcr2.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticOcr2.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=user]").suggest(emailSuggest.options);
            },

            bindEvent: function () {
                var self = this;
                self.bindDateTime();
                self.bindBasicEvent();
            },
            bindDateTime: function () {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000);
                var searchEnd = StatisticOcr2.Util.formatDateTimeFormat(currentDate);
                currentDate.setTime(currentDate.getTime() - 7 * 86400000);
                var searchStart = StatisticOcr2.Util.formatDateTimeFormat(currentDate);
                StatisticOcr2.Util.bindDate("startDate", "endDate", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=startDate]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));

                StatisticOcr2.Util.bindDate("liveBeginTime", "liveEndTime", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=liveBeginTime]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=liveEndTime]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));
            },

            bindBasicEvent: function () {
                var self = this;
                $("button[name=reset]").on("click", function (event) {
                    $("input[name=channelName]").suggest("setValue", "");
                    $("input[name=user]").suggest("setValue", "");
                    $("select[tag=form]").val("");
                    self.bindDateTime();
                });
                $('button.query-btn').on('click', function () {
                  //  self.getParam();
                    self.query();
                });
                $("button.query-excel").bind("click", function (event) {
                    StatisticOcr2.Util.doDownloadExcel();
                })
                $("button.query-batch").bind("click", function (event) {
                    StatisticOcr2.Util.doDownloadBatch();
                })
            },

            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },



            getParam: function () {
                var params = {};
                var inputArr =  $('form[name="basicFrm"]').find("input[type=text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("sql")] = element.value.trim()
                    }
                })
                var str = "";
                var selectArr = $('form[name="basicFrm"]').find("select[tag=form]")
                $.each(selectArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        str += element.value + ","
                    }
                })
                var arr = str.split(",");
                var single = null;
                $.each(arr,function(i,element){
                    single = element.split("=");
                    params[single[0]] = single[1];
                })
                console.log("params:="+JSON.stringify(params));
                return { paramsObj :JSON.stringify(params) };
            }

        });
    }
);

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticOcr2.Util.js
 * @path:   js-src/StatisticOcr/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define('../statisticOcr/StatisticOcr2.Util',['require','exports','module'],function (require, exports, module) {

    StatisticOcr2.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            addTime: function (v, o, r) {
                return v.split(" ")[0];
            },
            percent: function (v, o, r) {
                return v + "%";
            },
            ocrFlag: function (v, o, r) {
                if (v == 1) {
                    return "是";
                }
                return "否";
            },
            operator_download: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='StatisticOcr2.Util.downloadData(" + r.id + ")'>下载</a> ")
                return htmlArr.join("");
            },
            titleCharLen:function( v, o, r ){
                return v/2;
            }
        },
        doQueryAvgPercent: function () {
            var paramsObj = $("#list").jqGrid("getGridParam", "postData").paramsObj;
            if (paramsObj != null) {
                StatisticOcr2.Dao.getAvgAndFullPercent({ paramsObj: paramsObj }, function (data) {
                    $("#query_avg_loading").hide();
                    if (data != null && data.code == "A00000") {
                        if (Number(data.data.avg) >= 0) {
                            $("span[name=span_avg_percent]").html(Number(data.data.avg).toFixed(1) );
                            $("span[name=span_full_percent_rate]").html( Number(data.data.fullPercent).toFixed(1));
                            $("#query_avg_over").show();
                        }
                    } else {
                        EpgWeb.Plugin.showTips({content: "请求失败" + ( data == null ? "" : ":" + data.msg  ), type: "error"});
                        $("#query_avg_over").hide();
                    }
                })
            }
        },
        doDownloadExcel: function () {
            StatisticOcr2.Util.doFormGetFile(JSON.parse($("#list").jqGrid("getGridParam", "postData").paramsObj),false);
        },
        doDownloadBatch: function () {
           var idArr =  $('#list').jqGrid('getGridParam','selarrrow');
            if(idArr.length > 0){
                StatisticOcr2.Util.doFormGetFile({INL_id: idArr.join(",")},true);
            }
        },
        downloadData: function (elementId) {
            var dataArr = $("#list").jqGrid("getData");
            var findData = null;
            $.each(dataArr, function (i, element) {
                if (elementId == element.id) {
                    findData = element;
                    return false;
                }
            })
            if (findData != null) {
                StatisticOcr2.Util.doFormGetFile({EQL_id: findData.id},true);
            }
        },
        doFormGetFile: function (params,needPic) {
            var formElement = $('<form style="display: none"  method="get"></form>');
            formElement.attr("action", StatisticOcr2.urlConfig.getOcrExcelUrl);
            var paramsObj = JSON.stringify(params);
            var inputElement = $('<input name="paramsObj" >')
            inputElement.val(paramsObj);
            inputElement.appendTo(formElement );
            if(needPic == null||needPic === false){
                needPic = 0;
            }else{
                needPic = 1
            }
            var inputElement2 = $('<input name="needPic" value="'+needPic+'" >')
            inputElement2.appendTo( formElement );
            formElement.appendTo($("body"));
            formElement.submit().remove();
        }
    });

});

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 * 
 * @file:   StatisticAuto.js
 * @path:   js-src/StatisticOcr/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
	'../statisticAuto/StatisticAuto',['require','exports','module'],function(require, exports, module){
///import js-src/lib/
///import js-src/com/
window.StatisticAuto = window.StatisticAuto || { version : '1.0' };
        ///api/statistic/data/ocr/new
        StatisticAuto.Constant = {
            baseApiUrl: "/api/",
            thirdUrl_query_user:"http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_type: "http://lego.iqiyi.com/suggest/operation",
            devMode: auth.dev()
        }

        StatisticAuto.urlConfig = (function () {
            var useUrl = StatisticAuto.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var sdGetUrl = useUrl + "sd";
            var createUrl = useUrl + "statistic/auto/new";
            var newListUrl = useUrl + "statistic/auto/list";
            var queryDataRateUrl = useUrl + "statistic/auto/dataRate";
            var getAutoExcelUrl = useUrl + "statistic/download/autoExcel";
            var queryChannelName =(StatisticAuto.Constant.devMode ? "http://10.23.70.33:7000" : "http://10.23.70.219")+"/v1/channel/fuzzyquery";
            return {
                sdGetUrl: sdGetUrl,
                createUrl:createUrl,
                newListUrl:newListUrl,
                queryDataRateUrl:queryDataRateUrl,
                redirectUrl:redirectUrl,
                getAutoExcelUrl:getAutoExcelUrl,
                queryChannelName:queryChannelName

            }
        })()
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticAuto.Action.js
 * @path:   js-src/StatisticOcr/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
    '../statisticAuto/StatisticAuto.Action',['require','exports','module'],function(require, exports, module) {

        StatisticAuto.Action = (function() {

            //表格
            //统计OCR列表 old begin=====================
            var statisticGrid = null;

            var getStatisticGrid = function (options) {
                if (!statisticGrid) {
                    statisticGrid = new StatisticAuto.Grid($.extend(true,
                    {'$grid': $('#list'), type:0}, options))
                }
                return statisticGrid;
            }

            var statisticGridRun = function(options) {
                statisticGrid = getStatisticGrid(options);
                statisticGrid.init();
                console.log('grid run');
            }


            var run = function() {
              //  Ancestor.Config.EPG_AUTH.list='/statisticOcr/list';
                statisticGridRun({});
            }
            //统计OCR列表 old over=====================
            return {
                run:run,
                getStatisticOcrGrid:getStatisticGrid
            }
        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.Config.js
 * @path:   js-src/StatisticAuto/
 * @desc:   StatisticAuto公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */

define('../statisticAuto/StatisticAuto.Config',['require','exports','module'],function (require, exports, module) {
        StatisticAuto.Config = $.extend({}, Ancestor.Config, {

            TABLE_COLMODEL_CONFIG: {
                id: {
                    name: 'id',
                    index: 'id',
                    title: false,
                    width: 80,
                    align: 'center',
                    hidden: true,
                    sortable: false
                },
                user: {
                    name: 'user',
                    index: 'user',
                    width: 100,
                    align: 'center',
                    sortable: false,
                    title: false
                },
                channelName: {
                    name: 'channelName',
                    index: 'channelName',
                    width: 100,
                    align: 'center',
                    title: false,
                    sortable: false
                },
                userTitle: {
                    name: 'userTitle',
                    index: 'userTitle',
                    title: false,
                    width: 200,
                    sortable: false,
                    align: 'center'
                },
                autoTitle: {
                    name: 'autoTitle',
                    index: 'autoTitle',
                    title: false,
                    width: 200,
                    sortable: false,
                    align: 'center'
                },
                userTitleCharLen: {
                    name: 'userTitleCharLen',
                    index: 'userTitleCharLen',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return StatisticAuto.Util.formatter.titleCharLen(v, o, r);
                    }
                },
                autoTitleCharLen: {
                    name: 'autoTitleCharLen',
                    index: 'autoTitleCharLen',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return StatisticAuto.Util.formatter.titleCharLen(v, o, r);
                    }
                },
                autoFlag: {
                    name: 'autoFlag',
                    index: 'autoFlag',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticAuto.Util.formatter.autoFlag(v, o, r);
                    }
                },
                titleError: {
                    name: 'titleError',
                    index: 'titleError',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticAuto.Util.formatter.titleError(v, o, r);
                    }
                },
                percent: {
                    name: 'percent',
                    index: 'percent',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticAuto.Util.formatter.percent(v, o, r);
                    }
                },
                addTime: {
                    name: 'addTime',
                    index: 'addTime',
                    title: false,
                    sortable: false,
                    width: 80,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticAuto.Util.formatter.addTime(v, o, r);
                    }
                },
                legoProgramId: {
                    name: 'legoProgramId',
                    index: 'legoProgramId',
                    title: false,
                    sortable: false,
                    width: 100,
                    align: 'center'
                },
                liveBeginTime: {
                    name: 'liveBeginTime',
                    index: 'liveBeginTime',
                    title: false,
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                liveEndTime: {
                    name: 'liveEndTime',
                    index: 'liveEndTime',
                    title: false,
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                operator_download: {
                    title: false,
                    sortable: false,
                    width: 70,
                    align: 'center',
                    formatter: function (v, o, r) {
                        return  StatisticAuto.Util.formatter.operator_download(v, o, r);
                    }
                }
            },


            TABLE_AUTO_NEW: {
                url: StatisticAuto.urlConfig.newListUrl,
                multiselect: true,
                loadtext: '加载中...',
                loadui: 'block',
                rowNum: 20,
                loadBeforeSend: function (xhr, settings) {
                    var auth = Ancestor.Util.getAuth("/statistic/data/auto/new");
                    xhr.setRequestHeader('Sign', auth.sign);
                    xhr.setRequestHeader("Time", auth.clientTime);
                    xhr.setRequestHeader("From", auth.from);
                    return true;
                },
                datatype: "json",
                height: 450,
                caption: "自动识别统计列表",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                colNames: ["创建日期", "乐高节目ID", "编辑输入标题", "自动识别标题", "电视台", "制作人员", "使用自动\n识别标题", "输入标题\n字数", "识别标题字数", "标题检测是否错误", "标题文字准确率", "直播开始时间", "直播结束时间"],
                colModel: ['addTime', "legoProgramId", 'userTitle', 'autoTitle', 'channelName', 'user',
                    'autoFlag', 'userTitleCharLen', 'autoTitleCharLen', "titleError", 'percent', 'liveBeginTime', 'liveEndTime'],
                pager: "#pager",
                loadComplete: function () {
                    console.log(" loadComplete notify ");
                    $("#query_avg_loading").show();
                    $("#query_avg_over").hide();
                    if ($("#list").data("data") != null && $("#list").data("data").code == "A00000") {
                        $("span[name=span_total_num]").html($("#list").data("data").data.totalCount);
                        StatisticAuto.Util.doQueryAutoDataRate();
                    } else {
                        $("#query_avg_loading").hide();
                    }
                },
                gridComplete: function () {
                    console.log(" gridComplete notify ");
                }
            }
        });
    }
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticAuto.Dao.js
 * @path:   js-src/StatisticOcr/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
    '../statisticAuto/StatisticAuto.Dao',['require','exports','module'],function (require, exports, module) {

        StatisticAuto.Dao = $.extend({}, EpgWeb.Dao, {

            getDataRate: function (data, callback) {
                var options = {
                    url: StatisticAuto.urlConfig.queryDataRateUrl,
                    type: "post",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                        console.log("getDataRate ");
                    },
                    error: function (data) {
                        callback.call(this, data);
                        console.log("error getDataRate");
                    }
                }
                Ancestor.Dao.ajax(options, "/statistic/auto/dataRate");
            }
        });
    }
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticAuto.Base.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr模块下基础业对象类
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define(
    '../statisticAuto/StatisticAuto.Grid',['require','exports','module'],function (require, exports, module) {

        StatisticAuto.Grid = function (options) {
            this.dao = StatisticAuto.Dao;
            this.config = StatisticAuto.Config;
            this.options = options || {};
        };

        Com.inherits(StatisticAuto.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.bindEvent();
                self.initSuggest();
                self.initGrid();
            },
            initGrid: function (options, callback) {
                var self = this;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_AUTO_NEW);
                //params.rowNum=10;
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            initSuggest: function () {
            //    var self = this;
                var fuzzyQuerySuggest = {
                    options: {
                        source: StatisticAuto.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticAuto.urlConfig.queryChannelName, type: "get", params: {keyword: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }

                $("input[name=channelName]").suggest(fuzzyQuerySuggest.options)

                var emailSuggest = {
                    options: {
                        source: StatisticAuto.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: StatisticAuto.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=user]").suggest(emailSuggest.options);
            },

            bindEvent: function () {
                var self = this;
                self.bindDateTime();
                self.bindBasicEvent();
            },
            bindDateTime: function () {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000);
                var searchEnd = StatisticAuto.Util.formatDateTimeFormat(currentDate);
                currentDate.setTime(currentDate.getTime() - 7 * 86400000);
                var searchStart = StatisticAuto.Util.formatDateTimeFormat(currentDate);
                StatisticAuto.Util.bindDate("startDate", "endDate", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=startDate]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));

                StatisticAuto.Util.bindDate("liveBeginTime", "liveEndTime", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchStart, minDateTime: new Date(searchStart.replace(/-/g, "/"))});
                $("input[name=liveBeginTime]").datetimepicker("setDate", new Date(searchStart.replace(/-/g, "/")));
                $("input[name=liveEndTime]").datetimepicker("setDate", new Date(searchEnd.replace(/-/g, "/")));
            },

            bindBasicEvent: function () {
                var self = this;
                $("button[name=reset]").on("click", function (event) {
                    $("input[name=channelName]").suggest("setValue", "");
                    $("input[name=user]").suggest("setValue", "");
                    $("select[tag=form]").val("");
                    self.bindDateTime();
                });
                $('button.query-btn').on('click', function () {
                  //  self.getParam();
                    self.query();
                });
                $("button.query-excel").bind("click", function (event) {
                    StatisticAuto.Util.doDownloadExcel();
                })
                $("button.query-batch").bind("click", function (event) {
                    StatisticAuto.Util.doDownloadBatch();
                })
            },

            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },



            getParam: function () {
                var params = {};
                var inputArr =  $('form[name="basicFrm"]').find("input[type=text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("sql")] = element.value.trim()
                    }
                })
                var str = "";
                var selectArr = $('form[name="basicFrm"]').find("select[tag=form]")
                $.each(selectArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        str += element.value + ","
                    }
                })
                var arr = str.split(",");
                var single = null;
                $.each(arr,function(i,element){
                    single = element.split("=");
                    params[single[0]] = single[1];
                })
                console.log("params:="+JSON.stringify(params));
                return { paramsObj :JSON.stringify(params) };
            }

        });
    }
);

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticAuto.Util.js
 * @path:   js-src/StatisticAuto/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-06-26
 */
define('../statisticAuto/StatisticAuto.Util',['require','exports','module'],function (require, exports, module) {

    StatisticAuto.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            addTime: function (v, o, r) {
                return v.split(" ")[0];
            },
            percent: function (v, o, r) {
                return v + "%";
            },
            autoFlag: function (v, o, r) {
                if (v == 1) {
                    return "是";
                }
                return "否";
            },
            titleError: function (v, o, r) {
                if (v == 1) {
                    return "是";
                }
                return "否";
            },
            operator_download: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='StatisticAuto.Util.downloadData(" + r.id + ")'>下载</a> ")
                return htmlArr.join("");
            },
            titleCharLen:function( v, o, r ){
                return v/2;
            }
        },
        doQueryAutoDataRate: function () {
            var paramsObj = $("#list").jqGrid("getGridParam", "postData").paramsObj;
            if (paramsObj != null) {
                StatisticAuto.Dao.getDataRate({ paramsObj: paramsObj }, function (data) {
                    $("#query_avg_loading").hide();
                    if (data != null && data.code == "A00000") {
                        if (Number(data.data.avg) >= 0) {
                            $("span[name=span_used_percent]").html(Number(data.data.used).toFixed(1) );
                            $("span[name=span_error_percent]").html( Number(data.data.titleError).toFixed(1));
                            $("span[name=span_avg_percent]").html(Number(data.data.avg).toFixed(1) );
                            $("span[name=span_full_percent_rate]").html( Number(data.data.fullPercent).toFixed(1));
                            $("#query_avg_over").show();
                        }
                    } else {
                        EpgWeb.Plugin.showTips({content: "请求失败" + ( data == null ? "" : ":" + data.msg  ), type: "error"});
                        $("#query_avg_over").hide();
                    }
                })
            }
        },
        doDownloadExcel: function () {
            StatisticAuto.Util.doFormGetFile(JSON.parse($("#list").jqGrid("getGridParam", "postData").paramsObj),false);
        },
        doDownloadBatch: function () {
           var idArr =  $('#list').jqGrid('getGridParam','selarrrow');
            if(idArr.length > 0){
                StatisticAuto.Util.doFormGetFile({INL_id: idArr.join(",")},false);
            }
        },
        downloadData: function (elementId) {
            var dataArr = $("#list").jqGrid("getData");
            var findData = null;
            $.each(dataArr, function (i, element) {
                if (elementId == element.id) {
                    findData = element;
                    return false;
                }
            })
            if (findData != null) {
                StatisticAuto.Util.doFormGetFile({EQL_id: findData.id},false);
            }
        },
        doFormGetFile: function (params,needPic) {
            var formElement = $('<form style="display: none"  method="get"></form>');
            formElement.attr("action", StatisticAuto.urlConfig.getAutoExcelUrl);
            var paramsObj = JSON.stringify(params);
            var inputElement = $('<input name="paramsObj" >')
            inputElement.val(paramsObj);
            inputElement.appendTo(formElement );
            if(needPic == null||needPic === false){
                needPic = 0;
            }else{
                needPic = 1
            }
            var inputElement2 = $('<input name="needPic" value="'+needPic+'" >')
            inputElement2.appendTo( formElement );
            formElement.appendTo($("body"));
            formElement.submit().remove();
        }
    });

});

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 * 
 * @file:   StatisticSty2.js
 * @path:   js-src/StatisticSty2/
 * @author: zhang@qiyi.com
 * @date:   2016-04-25
 */
define(
	'../statisticSty2/StatisticSty2',['require','exports','module'],function(require, exports, module){

        window.StatisticSty2 = window.StatisticSty2 || { version : '1.0' };

        StatisticSty2.queryStringObj = function() {
            //取浏览器参数
            var url = window.location.href;

            var queryStringArr = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+","g")),
            	 queryStringObj = {}
            	 itemArr = [];

            for(var i = 0; i < queryStringArr.length; i++){
                itemArr = queryStringArr[i].substring(1).split("=");
                queryStringObj[itemArr[0]] = itemArr[1];
            }

            return queryStringObj;
        };
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2.Action.js
 * @path:   js-src/StatisticSty2/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
    '../statisticSty2/StatisticSty2.Action',['require','exports','module'],function(require, exports, module) {

        StatisticSty2.Action = (function() {

            //表格
            var statisticSty2Grid = null;

            var getStatisticSty2Grid = function (options) {
                if (!statisticSty2Grid) {
                    statisticSty2Grid = new StatisticSty2.Grid($.extend(true,
                    {'$container': $('#StatisticSty2ListContainer'), $hiddenGrid: $("#hiddenGrid"), type:0}, options))
                }

                return statisticSty2Grid;
            }

            var statisticSty2GridRun = function(options) {
                statisticSty2Grid = getStatisticSty2Grid(options);
                statisticSty2Grid.run();

                console.log('grid run');
            }

            //统计Sty2列表
            var run = function() {
                Ancestor.Config.EPG_AUTH.list='/statisticSty2/list';
                statisticSty2GridRun({});
            }

            return {
                run:run,
                getStatisticSty2Grid:getStatisticSty2Grid
            }
        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Channel.Config.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
///import js-src/lib/
///import js-src/com/
define('../statisticSty2/StatisticSty2.Config',['require','exports','module'],function(require, exports, module){
        StatisticSty2.Config = $.extend({}, Ancestor.Config, {

            TABLE_COLMODEL_CONFIG: {
                channelId: {
                    name: 'channelId',
					index:'channelId',
                    title: false,
                    width: 80,
				    align: 'center',
				    hidden: true,
					sortable: false
                },
                channelName: {
                    name: 'channelName',
					index:'channelName',
                    title: false,
                    width: 80,
				    align: 'center',
					sortable: false
                },
                channelCode: {
                    name: 'channelCode',
					index:'channelCode',
                    title: false,
                    width: 80,
				    align: 'center',
				    hidden: true,
					sortable: false
                },
                programId: {
                    name: 'programId',
					index:'programId',
                    title: false,
                    width: 80,
				    align: 'center',
				    hidden: true,
					sortable: false
                },
                programName: {
                    name: 'programName',
					index:'programName',
                    title: false,
                    width: 80,
				    align: 'center',
					sortable: false
                },
                categoryName: {
                    name: 'categoryName',
                    index: 'categoryName',
                    width: 100,
                    align: 'center',
                    title: false,
                    sortable: false
                },
                albumName: {
                    name: 'albumName',
					index:'albumName',
                    title: false,
                    width: 80,
				    align: 'center',
					sortable: false
                },
                programTime: {
                    name: 'programTime',
					index:'programTime',
                    title: false,
                    width: 100,
				    align: 'center',
					sortable: false,
					formatter:function(v, o, r){
					    return StatisticSty2.Util.programMinutes(v, o, r);
					}
                },
                headerCompleteNumbers: {
                    name: 'headerCompleteNumbers',
                    index:'headerCompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                headerIncompleteNumbers: {
                    name: 'headerIncompleteNumbers',
                    index:'headerIncompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                headerFaultNumbers: {
                    name: 'headerFaultNumbers',
                    index:'headerFaultNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                lastCompleteNumbers: {
                    name: 'lastCompleteNumbers',
                    index:'lastCompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                lastIncompleteNumbers: {
                    name: 'lastIncompleteNumbers',
                    index:'lastIncompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                lastFaultNumbers: {
                    name: 'lastFaultNumbers',
                    index:'lastFaultNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                adCompleteNumbers: {
                    name: 'adCompleteNumbers',
                    index:'adCompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                adIncompleteNumbers: {
                    name: 'adIncompleteNumbers',
                    index:'adIncompleteNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                adFaultNumbers: {
                    name: 'adFaultNumbers',
                    index:'adFaultNumbers',
                    title: false,
                    width: 100,
                    align: 'center',
                    sortable: false
                },
                user: {
                    name: 'user',
					index:'user',
                    width: 80,
					align: 'center',
                    sortable: false,
                    title: false
                },
                statisticTime: {
                    name: 'statisticTime',
                    index:'statisticTime',
                    title: false,
					sortable: false,
                    width: 120,
                    align: 'center'
                },
            },

            TABLE: { //列表配置
                url: '/api/statisticSty2/list',
				//datatype:"jsonp",
				multiselect: false,
					
				loadtext:'加载中...',
				loadui:'block',
				rowNum:20,

                loadBeforeSend:function(xhr, settings){
                    var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                    xhr.setRequestHeader('Sign',auth.sign);
                    xhr.setRequestHeader("Time",auth.clientTime);
                    xhr.setRequestHeader("From",auth.from);
                    return true;
                },
				
				prmNames :{
					 page:"pageNo",
					 rows:"pageSize",    
				 },

                colNames: ["频道ID", "节目ID","所属电视台代码","节目原名","所属专辑", "频道","所属电视台","节目时长(时分秒)","片头完全准确数","片头部分准确数","片头不准确数","片尾完全准确数","片尾部分准确数","片尾不准确数","广告完全准确数","广告部分准确数","广告不准确数","制作者","创建时间"],

                colModel: ['channelId', 'programId', 'channelCode','programName', 'albumName', 'categoryName','channelName','programTime','headerCompleteNumbers','headerIncompleteNumbers','headerFaultNumbers','lastCompleteNumbers','lastIncompleteNumbers','lastFaultNumbers','adCompleteNumbers','adIncompleteNumbers','adFaultNumbers','user','statisticTime']
            },

            TABLE_HIDDEN: {
                colNames: ["节目ID","节目原名","所属专辑", "频道","所属电视台","节目时长(时分秒)",
                    "片头完全准确数","片头部分准确数","片头不准确数","片尾完全准确数","片尾部分准确数","片尾不准确数",
                    "广告完全准确数","广告部分准确数","广告不准确数","制作者","创建时间"
                    ],

                colModel: ['programId','programName','albumName','categoryName','channelName','programTime',
                    'headerCompleteNumbers','headerIncompleteNumbers','headerFaultNumbers',
                    'lastCompleteNumbers','lastIncompleteNumbers','lastFaultNumbers',
                    'adCompleteNumbers','adIncompleteNumbers','adFaultNumbers','user','statisticTime'
                    ]

            }
        });
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2.Dao.js
 * @path:   js-src/StatisticSty2/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: zhang@qiyi.com
 * @date:   2015-01-07
 */
define(
	'../statisticSty2/StatisticSty2.Dao',['require','exports','module'],function(require, exports, module){

        StatisticSty2.Dao = $.extend({}, Ancestor.Dao, {
            getExportData: function (data, callback) {
                var options = {
                    url: "/api/statisticSty2/list",
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/statisticSty2/list');
            },

            getExportDataAll: function (params, handler) {
                var daoSelf = this;
                params.pageNo = 1;
                handler.lockHandler();
                var queryComponent = {
                    params: params,
                    dataArr: [],
                    phase:0,
                    hasFlushNum:0,
                    query: function () {
                        var self = this;
                        daoSelf.getExportData(params, function (data) {
                            if (data == null) {
                                EpgWeb.Plugin.showTips({content: "请求失败", type: "error"  })
                                handler.phaseHandler(self.dataArr);
                                handler.unlockHandler();
                            } else {
                                self.dataArr = self.dataArr.concat(data.data.result);
                                self.phase++;
                                handler.phaseHandler(self.dataArr,"phase"+self.phase);
                                console.log("self.phase:"+self.phase);
                                self.hasFlushNum += self.dataArr.length;
                                self.dataArr = [];
                                if (self.hasFlushNum < data.data.totalCount) {
                                    self.params["pageNo"] = params.pageNo + 1;
                                    console.log("params.pageNo:"+self.params["pageNo"]);
                                    self.query();
                                }else{
                                    handler.unlockHandler();
                                }
                            }
                        })
                    }
                };
                queryComponent.query();
            }
        });
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2.Base.js
 * @path:   js-src/StatisticSty2/
 * @desc:   StatisticSty2模块下基础业对象类
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
	'../statisticSty2/StatisticSty2.Grid',['require','exports','module'],function(require, exports, module){

        StatisticSty2.Grid = function(options) {
            this.dao = StatisticSty2.Dao;
            this.config = StatisticSty2.Config;
            this.options = options || {};
            this.exportExcel = false;
        };

        Com.inherits(StatisticSty2.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$hiddenGrid = self.options.$hiddenGrid;
                self.$grid = $container.find('table.grid');
                self.queryStringObj = StatisticSty2.queryStringObj();
                self.bindEvent();
                self.initSuggest();
            },


			run : function()
			{

                this.start();

			},
		
            start: function(options, callback) {
                var self = this;
				self.init();
				
                var gridConfig = self.getGridConfig();
					//self.echoQuery();
				
                options = $.extend(true, {
                      width: 1500,
                  //  shrinkToFit: false,
                    //autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);

				$('body').on('click','a.disabled',function(e){
				  e.preventDefault();
				});

            },

            initGrid: function(options, callback) {
				var self = this;
				var params = self.getParam();			

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

				//params.rowNum=10;
				
                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',
					
                   postData: $.extend(true, {}, params),
				   
                }, gridConfig, options);
				
             //   $grid.jqGrid('scroll', {});
				
				//console.log(options	);
				
                $grid.jqGrid(options);

            },
            initSuggest:function(){

                var emailSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search", type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=user]").suggest(emailSuggest.options);

                var programNameSuggest = {
                    options: {
                        source: "/api/suggest/statisticSty2",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            return {"field": "programName", timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item;
                                itemData[options.labelKey] = item;
                                itemData["value"]= item;
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=programName]").suggest(programNameSuggest.options);
            },
			jsonConvert : function (jsonstr,o){
                    if (jsonstr && typeof jsonstr === 'string') {
						var _jsonparse = false;
						if($.jgrid.useJSON) {
							$.jgrid.useJSON = false;
							_jsonparse = true;
						}
                        var json = $.jgrid.parse(jsonstr);
						if(_jsonparse) { $.jgrid.useJSON = true; }
                        var gprm = json[o.jsonGrid.config];
                        var jdata = json[o.jsonGrid.data];
                        if(jdata) {
                            var svdatatype = gprm.datatype;
                            gprm.datatype = 'jsonstring';
                            gprm.datastr = jdata;
                            $($t).jqGrid( gprm ).jqGrid("setGridParam",{datatype:svdatatype});
                        } else {
                            $($t).jqGrid( gprm );
                        }
                    }
                },
            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
	
                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },


            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function() {
                    return true; //this.name; 
                });

                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {

                            if(this.type=='radio')
							{	
								params[name] = $('input[name="'+name+'"]:checked').val() || '';
							}
							else
                            params[name] = $.trim($(this).val()) || '';
                    }

                });

                var queryStringObj = self.queryStringObj;
                if (queryStringObj['channelId']) {
                    $.extend(params, {channelId : queryStringObj['channelId']});
                }
                if (queryStringObj['albumName']) {
                    $.extend(params, {albumName : decodeURIComponent(queryStringObj['albumName'])});
                }
                if (queryStringObj['categoryName']) {
                    $.extend(params, {categoryName : decodeURIComponent(queryStringObj['categoryName'])});
                }
                return params;
            },

            bindEvent: function() {
                var self = this;
                self.bindBasicEvent();
            },



            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                self.bindFormData($form);

                $container.find('.query-btn').on('click.query', function() {
				    self.query();
                    return false;
                });

                $("div.query").keydown(function(event){
                    if(event.keyCode == 13)
                    {
                            self.query();
                            return false;
                    }
                });

                $form.find('button[name="reset"]').click(function() {
                    var $elements = $.makeArray($form.prop('elements')).filter(function() {
                        return true; //this.name;
                    });
                    var name;
                    $.each($elements, function() {
                        name = this.name;
                        if (name) {
                                $.trim($(this).val(""));
                        }
                    });
                    self.bindFormData($form);
                });

                $container.find("button.query-excel").bind("click", function (event) {
                    self.$hiddenGrid.html("");
                    $("button.query-excel").prop("disabled", "disabled")
                    self.doExportExcel();
                })

            },
            doExportExcel: function () {
                var self = this;
                var params = self.getParam();
                params.pageSize = 5000;
                self.dao.getExportDataAll(params,{
                    lockHandler:function(){
                        $("button.query-excel").prop("disabled", "disabled")
                    },
                    flushCheck:function(curNum){
                        return curNum >= 5000
                    },
                    phaseHandler:function (dataArr,fileName) {
                        self.doExportExcelAllCallBack(dataArr,"长视频智能分析");
                    },
                    unlockHandler:function(){
                        $("button.query-excel").removeAttr("disabled")
                    }
                });
            },
            doExportExcelAllCallBack: function (dataArr, fileName) {
                var self = this
                if (dataArr != null && dataArr.length > 0) {
                    self.$hiddenGrid.append(StatisticSty2.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(dataArr, function (i, element) {
                        self.$hiddenGrid.append(StatisticSty2.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                if (fileName != null) {
                    self.$hiddenGrid.tableToExcel({name: fileName});
                } else {
                    self.$hiddenGrid.tableToExcel();
                }
                self.$hiddenGrid.html("");
            },
            doExportExcelCallBack: function (data) {
                var self = this
                if (data != null && data.data.result.length > 0) {
                    self.$hiddenGrid.append(StatisticSty2.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(data.data.result, function (i, element) {
                        self.$hiddenGrid.append(StatisticSty2.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                self.$hiddenGrid.tableToExcel();
                self.$hiddenGrid.html("");
                console.log("excel build end");
                $("button.query-excel").removeAttr("disabled")
            },

            bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "minDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "maxDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="categoryName"]').keydown(function(event){

                });

				fillFieldNameWhenChangeSelect($form, 'query-select-control', 'query-input-text');
			},

            bindFormData: function($form) {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000 );
                var searchEnd = currentDate.format("yyyy-MM-dd hh:mm:ss");
                currentDate.setTime(currentDate.getTime() - 7*86400000 );
                var searchBegin = currentDate.format("yyyy-MM-dd hh:mm:ss");
                $("input[name=endDate]").datetimepicker("option", "minDate", searchBegin);
                $("input[name=endDate]").datetimepicker("option", "minDateTime", new Date(searchBegin.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("option", "maxDate", searchEnd);
                $("input[name=startDate]").datetimepicker("option", "maxDateTime", new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate",new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("setDate",new Date(searchBegin.replace(/-/g, "/")));
            },
        });

	}
);

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2.Util.js
 * @path:   js-src/StatisticSty2/
 * @desc:
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define('../statisticSty2/StatisticSty2.Util',['require','exports','module'],function(require, exports, module){

    StatisticSty2.Util = $.extend(true, {}, {

        programMinutes: function (v, o, r) {
            var duration = v;
            var darArr = [];
            darArr.push(duration % 60);
            duration = ( duration - duration % 60) / 60;
            darArr.push(duration % 60);
            duration = ( duration - duration % 60) / 60;
            darArr.push(duration);
//                    duration = ( duration - duration % 24) / 24;
//                    if (duration > 0) {
//                        darArr.push(duration);
//                    }
            var retValue = "";
            switch (darArr.length) {
                case 3:
                    retValue += darArr[2] <= 0 ? "" : darArr[2] + "时";
                case 2:
                    retValue += darArr[1] <= 0 ? "" : darArr[1] + "分";
                case 1:
                    retValue += darArr[0] <= 0 ? "" : darArr[0] + "秒";
                    break;
            }
            if(retValue.length == 0){
                retValue = "0秒";
            }
            return retValue;
        },
        buildTH: function (dataArr) {
            var retValue = [];
            $.each(dataArr, function (i, element) {
                retValue.push("<td>" + element + "</td>");
            });
            return "<tr>" + retValue.join("") + "</tr>";
        },

        buildTD: function (object, keyArr) {
            var retValue = [];
            $.each(keyArr, function (index, element) {
                var configData = StatisticSty2.Config.TABLE_COLMODEL_CONFIG[element]
                if (configData.formatter != null) {
                    retValue.push("<td>" + configData.formatter(object[configData.name], null, object) + "</td>");
                } else {
                    retValue.push("<td>" + object[configData.name] + "</td>");
                }
            });
            return "<tr>" + retValue.join("") + "</tr>";
        }
	});

});

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 * 
 * @file:   StatisticSty2Percent.js
 * @path:   js-src/StatisticSty2/
 * @author: zhang@qiyi.com
 * @date:   2016-04-25
 */
define(
	'../statisticSty2/StatisticSty2Percent',['require','exports','module'],function(require, exports, module){

 
///import js-src/lib/
///import js-src/com/

window.StatisticSty2Percent = window.StatisticSty2Percent || { version : '1.0' };


	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2Percent.Action.js
 * @path:   js-src/StatisticSty2/
 * @desc:   Action静态对象，声明对象以及绑定事件、对外接口等
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
    '../statisticSty2/StatisticSty2Percent.Action',['require','exports','module'],function(require, exports, module) {

        StatisticSty2Percent.Action = (function() {

            //表格
            var statisticSty2PercentGrid = null;

            var getStatisticSty2PercentGrid = function (options) {
                if (!statisticSty2PercentGrid) {
                    statisticSty2PercentGrid = new StatisticSty2Percent.Grid($.extend(true,
                    {'$container': $('#StatisticSty2PercentListContainer'), type:0}, options))
                }

                return statisticSty2PercentGrid;
            }

            var statisticSty2PercentGridRun = function(options) {
                statisticSty2PercentGrid = getStatisticSty2PercentGrid(options);
                statisticSty2PercentGrid.run();

                console.log('grid run');
            }

            //统计Sty2列表
            var run = function() {
                Ancestor.Config.EPG_AUTH.list='/statisticSty2Percent/list';
                statisticSty2PercentGridRun({});
            }

            return {
                run:run,
                getStatisticSty2PercentGrid:getStatisticSty2PercentGrid
            }
        })();
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Channel.Config.js
 * @path:   js-src/StatisticOcr/
 * @desc:   StatisticOcr公共配置集合，键值对象
 *          一级键名大写，之间名采用驼峰式
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
///import js-src/lib/
///import js-src/com/
define('../statisticSty2/StatisticSty2Percent.Config',['require','exports','module'],function(require, exports, module){
        StatisticSty2Percent.Config = $.extend({}, Ancestor.Config, {

            TABLE_COLMODEL_CONFIG: {
                channelId: {
                    name: 'channelId',
                    index:'channelId',
                    title: false,
                    width: 80,
                    align: 'center',
                    hidden: true,
                    sortable: false
                },
                channelName: {
                    name: 'channelName',
					index:'channelName',
                    title: false,
                    width: 80,
				    align: 'center',
					sortable: false
                },
                categoryName: {
                    name: 'categoryName',
                    index: 'categoryName',
                    width: 80,
                    align: 'center',
                    title: false,
                    sortable: false
                },
                albumName: {
                    name: 'albumName',
					index:'albumName',
                    title: false,
                    width: 80,
				    align: 'center',
					sortable: false
                },
                headerCompletePercent: {
                    name: 'headerCompletePercent',
                    index:'headerCompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                headerIncompletePercent: {
                    name: 'headerIncompletePercent',
                    index:'headerIncompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                headerFaultPercent: {
                    name: 'headerFaultPercent',
                    index:'headerFaultPercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                lastCompletePercent: {
                    name: 'lastCompletePercent',
                    index:'lastCompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                lastIncompletePercent: {
                    name: 'lastIncompletePercent',
                    index:'lastIncompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                lastFaultPercent: {
                    name: 'lastFaultPercent',
                    index:'lastFaultPercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                adCompletePercent: {
                    name: 'adCompletePercent',
                    index:'adCompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                adIncompletePercent: {
                    name: 'adIncompletePercent',
                    index:'adIncompletePercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                adFaultPercent: {
                    name: 'adFaultPercent',
                    index:'adFaultPercent',
                    title: false,
                    width: 120,
                    align: 'center',
                    sortable: false
                },
                sty2: {
                    align: 'center',
                    formatter: function(v, o, r) {
                        return StatisticSty2Percent.Util.formatter.sty2(v, r)
                    }
                }
            },

            TABLE: { //列表配置
                url: '/api/statisticSty2Percent/list',
				//datatype:"jsonp",
				multiselect: false,
					
				loadtext:'加载中...',
				loadui:'block',

                loadBeforeSend:function(xhr, settings){
                    var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                    xhr.setRequestHeader('Sign',auth.sign);
                    xhr.setRequestHeader("Time",auth.clientTime);
                    xhr.setRequestHeader("From",auth.from);
                    return true;
                },
				
				prmNames :{
					 page:"pageNo",
					 rows:"pageSize",    
				 },
                jsonReader:{
                    root:"data"
                },
                colNames: ["频道ID","专辑名称", "频道","所属电视台","片头完全准确率（数）","片头部分准确率（数）","片头不准确率（数）","片尾完全准确率（数）","片尾部分准确率（数）","片尾不准确率（数）","广告完全准确率（数）","广告部分准确率（数）","广告不准确率（数）","详细数据"],

                colModel: ['channelId','albumName', 'categoryName','channelName','headerCompletePercent','headerIncompletePercent','headerFaultPercent','lastCompletePercent','lastIncompletePercent','lastFaultPercent','adCompletePercent','adIncompletePercent','adFaultPercent','sty2']
            },

        });
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2Percent.Dao.js
 * @path:   js-src/StatisticSty2/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: zhang@qiyi.com
 * @date:   2015-01-07
 */
define(
	'../statisticSty2/StatisticSty2Percent.Dao',['require','exports','module'],function(require, exports, module){
	}
);
/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2Percent.Base.js
 * @path:   js-src/StatisticSty2/
 * @desc:   StatisticSty2模块下基础业对象类
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define(
	'../statisticSty2/StatisticSty2Percent.Grid',['require','exports','module'],function(require, exports, module){

        StatisticSty2Percent.Grid = function(options) {
            this.dao = StatisticSty2Percent.Dao;
            this.config = StatisticSty2Percent.Config;
            this.options = options || {};
        };

        Com.inherits(StatisticSty2Percent.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
                self.initSuggest();
            },


			run : function()
			{

                this.start();

			},
		
            start: function(options, callback) {
                var self = this;
				self.init();
				
                var gridConfig = self.getGridConfig();
					//self.echoQuery();
				
                options = $.extend(true, {
                      width: 1500,
                  //  shrinkToFit: false,
                    //autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);

				$('body').on('click','a.disabled',function(e){
				  e.preventDefault();
				});

            },

            initGrid: function(options, callback) {
				var self = this;
				var params = self.getParam();			
				
                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $grid = $gridContainer.find('table.grid');
               
				//params.rowNum=10;
				
                options = $.extend(true, {
                    mtype: 'post',
					
                   postData: $.extend(true, {}, params),
				   
                }, gridConfig, options);

				
                $grid.jqGrid(options);

            },
            initSuggest:function(){
                var channelTypeSuggest = {
                    options:{
                        source:"/api/redirect",
                        renderPanel:function(handler){
                            var ajaxOptions={
                                type:"post",
                                url:"/api/redirect",
                                dataType:"json",
                                data:  {"request": JSON.stringify({url: "http://lego.iqiyi.com/suggest/operation", type: "get", params:{size:50} , needCookie: true}), timeSign: new Date().getTime()},
                                success: function (data) {
                                    var formatData = [];
                                    $.each(data.data,function(i,element){
                                        formatData.push({id:element.id,label:element.name,value:element.name})
                                    })
                                    handler(formatData);
                                    console.log("renderPanel happen");
                                },
                                error:function(data){
                                    console.log("error happen");
                                }
                            };
                            $.ajax(ajaxOptions)
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size:50}:{word: term,size:50}
                            var requestData = {url:  "http://lego.iqiyi.com/suggest/operation", type: "get", params:params , needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"]= item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=categoryName]").suggest(channelTypeSuggest.options)

                var fuzzyQuerySuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: auth.dev() ? "http://10.23.70.33:7000/v1/channel/fuzzyquery" : "http://dot.live.qiyi.domain/v1/channel/fuzzyquery", type: "get", params: {keyword: term}};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }
                $("input[name=channelName]").suggest(fuzzyQuerySuggest.options);

                var albumNameSuggest = {
                    options: {
                        source: "/api/suggest/statisticSty2",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            return {"field": "albumName", timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item;
                                itemData[options.labelKey] = item;
                                itemData["value"]= item;
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=albumName]").suggest(albumNameSuggest.options);
            },
			jsonConvert : function (jsonstr,o){
                    if (jsonstr && typeof jsonstr === 'string') {
						var _jsonparse = false;
						if($.jgrid.useJSON) {
							$.jgrid.useJSON = false;
							_jsonparse = true;
						}
                        var json = $.jgrid.parse(jsonstr);
						if(_jsonparse) { $.jgrid.useJSON = true; }
                        var gprm = json[o.jsonGrid.config];
                        var jdata = json[o.jsonGrid.data];
                        if(jdata) {
                            var svdatatype = gprm.datatype;
                            gprm.datatype = 'jsonstring';
                            gprm.datastr = jdata;
                            $($t).jqGrid( gprm ).jqGrid("setGridParam",{datatype:svdatatype});
                        } else {
                            $($t).jqGrid( gprm );
                        }
                    }
                },
            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
	
                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },


            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function() {
                    return true; //this.name; 
                });

                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {

                            if(this.type=='radio')
							{	
								params[name] = $('input[name="'+name+'"]:checked').val() || '';
							}
							else
                            params[name] = $.trim($(this).val()) || '';
                    }

                });
                
                return params;

            },

            bindEvent: function() {
                var self = this;
                self.bindBasicEvent();
            },



            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                self.bindFormData($form);

                $container.find('.query-btn').on('click.query', function() {
				    self.query();
                    return false;
                });

                $("div.query").keydown(function(event){
                    if(event.keyCode == 13)
                    {
                            self.query();
                            return false;
                    }
                });

                $form.find('button[name="reset"]').click(function() {
                    var $elements = $.makeArray($form.prop('elements')).filter(function() {
                        return true; //this.name;
                    });
                    var name;
                    $.each($elements, function() {
                        name = this.name;
                        if (name) {
                                $.trim($(this).val(""));
                        }
                    });
                    self.bindFormData($form);
                });

            },

            bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "minDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "maxDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="categoryName"]').keydown(function(event){

                });

				fillFieldNameWhenChangeSelect($form, 'query-select-control', 'query-input-text');
			},
            bindFormData: function($form) {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000 );
                var searchEnd = currentDate.format("yyyy-MM-dd hh:mm:ss");
                currentDate.setTime(currentDate.getTime() - 7*86400000 );
                var searchBegin = currentDate.format("yyyy-MM-dd hh:mm:ss");
                $("input[name=endDate]").datetimepicker("option", "minDate", searchBegin);
                $("input[name=endDate]").datetimepicker("option", "minDateTime", new Date(searchBegin.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("option", "maxDate", searchEnd);
                $("input[name=startDate]").datetimepicker("option", "maxDateTime", new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate",new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("setDate",new Date(searchBegin.replace(/-/g, "/")));
            }
        });

	}
);

/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2Percent.Util.js
 * @path:   js-src/StatisticSty2/
 * @desc:
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
define('../statisticSty2/StatisticSty2Percent.Util',['require','exports','module'],function(require, exports, module){

    StatisticSty2Percent.Util = $.extend(true, {}, {
        formatter: {
            sty2: function(v, r) {
                return '<a href="./statistic_sty2.html?channelId=' + r.channelId +'&albumName=' + r.albumName +'&categoryName=' + r.categoryName +'" target="_blank">每集详情</a>';
            }
        }
	});

});

define(
	'../preSet/PreSet',['require','exports','module'],function(require, exports, module){
		window.PreSet = window.PreSet || { version : '1.0' };
		//Video公共配置集合，键值对象
		PreSet.Config = PreSet.Config || {};
		PreSet.Util = PreSet.Util || {};

        PreSet.Constant = {
            ipListUrl:(auth.dev() ? "http://10.23.70.33:7000/v1/channel/machinelist" : "http://dot.live.qiyi.domain/v1/channel/machinelist"),
            preRecocordUrl:(auth.dev() ? "http://10.23.70.33:7007/v1/ablum/prerecord" : "http:dot.live.qiyi.domainom/v1/ablum/prerecord"),
            preSetApi:(auth.dev() ? "http://10.23.70.33:7007/v1/ablum" : "httdot.live.qiyi.domain.com/v1/ablum")
        }
	}
);
define(
	'../preSet/PreSet.Action',['require','exports','module'],function(require, exports, module){

        PreSet.Action = (function() {
			var preSetGrid = null;
            var getPreSetGrid = function(options) {
                if (!preSetGrid) {

                    preSetGrid = new PreSet.Grid($.extend(true, {
                        '$container': $('#PreSetListContainer'),
                        type: 0
                    }, options));
                }
                return preSetGrid;
            };
            var preSetGridRun = function(options) {
                preSetGrid = getPreSetGrid(options);
                preSetGrid.run();
            };
			var run = function() {
                /* videoQueryRun();*/
                preSetGridRun({});
            };
            var editBase = null;
            var getEditBase = function(options) {

                if (!editBase) {
                    editBase = new PreSet.Edit(options);
                }
                return editBase;
            };
            var editRun = function() {
                var $container = $('.video-edit-form');
                getEditBase({
                    $container: $container
                }).run();
            };
            return {
                run: run,
				editRun:editRun,
				getPreSetGrid:getPreSetGrid
            };
        })();
	}
);
define('../preSet/PreSet.Config',['require','exports','module'],function(require, exports, module) {

    PreSet.Config = {

		REPEAT_INFO : ["周一","周二","周三","周四","周五","周六","周日"], //播放日期
		PRIORITY : ["低","中","高","紧急"],    //优先级
		PRIORITY_VALUE : ["0", "1", "2", "3"],
		SCALE : ["保持原有比例","16：9","4：3"],       //宽高比
		SCALE_VALUE : ["", "16x9", "4x3"],


        validator: {
                messages: {
                    "thriftVideo.albumId": {
                        "required": "专辑不能为空"
                    },
                    "repeat_info": {
                        "required": '播放日期不能为空'
                    },
                    "scale": {
                        "required": '宽高比不能为空'
                    },
                    "start_time": {
                        "required": '节目开始时间不能为空',
						isValidTime: "格式为：12:30:20"
                    },
                    "stop_time": {
                        "required": '节目结束时间不能为空',
						isValidTime: "格式为：13:30:20"
                    },
                    "priority": {
                        "required": '转码优先级'
                    }
                },
                rules: {
                    "thriftVideo.albumId": {
						"required": true
                    },
                    "repeat_info": {
						"required": true
                    },
                    "scale": {
						"required": true
                    },
                    "start_time": {
						"required": true,
						isValidTime: true
                    },
                    "stop_time": {
						"required": true,
						isValidTime: true
                    },
                    "priority": {
						"required": true
                    }
                }
            },


			TABLE_COLMODEL_CONFIG: {
				'ablum_name': {
					name: 'ablum_name',
					title: false,
					index: 'ablum_name',
					sortable: false,
					width: 140
				},
				'repeat_info': {
					name: 'repeat_info',
					title: false,
					index: 'repeat_info',
					align:'center',
					width: 230,
					sortable: false,
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.repeatInfo(v,r);
					}
				},
				'start_time': {
					name: 'start_time',
					title: false,
					index: 'start_time',
					sortable: false,
					width: 100,
					align: 'center'
				},
				'stop_time': {
					name: 'stop_time',
					title: false,
					index: 'stop_time',
					width: 100,
					sortable: false,
					align: 'center'
				},
				'scale': {
					name: 'scale',
					title: false,
					index: 'scale',
					align:'center',
					sortable: false,
					width: 100,
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.scale(v,r);
					}
				},
				'priority': {
					name: 'priority',
					index: 'priority',
					sortable: false,
					align:'center',
					width: 90,
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.priority(v,r);
					}

				},
				'video_head': {
					name: 'video_head',
					index: 'video_head',
					sortable: false,
					width: 130,
					align: 'center',
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.videoHead(v,r);
					}
				},
				'video_tail': {
					name: 'video_tail',
					index: 'video_tail',
					sortable: false,
					width: 130,
					align: 'center',
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.videoTail(v,r);
					}
				},
				'ad_libary': {
					name: 'ad_libary',
					index: 'ad_libary',
					sortable: false,
					width: 130,
					align: 'center',
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.adLibary(v,r);
					}
				},
				'score': {
					name: 'score',
					index: 'score',
					sortable: false,
					align:'center',
					width: 130,
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.score(v,r);
					}
				},
				'avg_score': {
					name: 'avg_score',
					title: false,
					index: 'avg_score',
					sortable: false,
					align:'center',
					width: 130,
					formatter: function(v, o, r) {
						return PreSet.Util.formatter.avgScore(v,r);
					}


				},
				'operate': {
					name: 'operate',
					title: false,
					index: 'operate',
					width: 140,
					align:'center',
					sortable: false,

					formatter: function(v, o, r) {
						return PreSet.Util.formatter.operate(v,r);
					}
				}
			},

			TABLE: {
			    url: "/api/redirect",
			    datatype: "local",
			    loadtext: '加载中...',
                loadui: "block",
                mtype: "post",
				colNames: ["专辑名称", "播放时间", "开始时间", "结束时间", "宽高比", "优先级", "片头库", "片尾库",
				"广告库","最新节目准确率","平均准确率（最近30天）","操作"
				],
				colModel: ['ablum_name', 'repeat_info', 'start_time', 'stop_time', 'scale', 'priority',
				'video_head', 'video_tail','ad_libary', 'score', 'avg_score','operate'
				]
			}
		};
});
define(
	'../preSet/PreSet.Dao',['require','exports','module'],function(require, exports, module){


        PreSet.Dao = $.extend({}, Ancestor.Dao, {
            save: function(data, callback) {
                $.ajax({
                    url:'/live2VOD/preSet/save',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                });
            },

            del: function(data, callback) {
                var url = PreSet.Constant.preSetApi + "/modify";
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                });
            },

            saveAssociation: function(data, callback) {

				var url = PreSet.Constant.preRecocordUrl;

                $.ajax({
                    url:url,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                });
            },

            //获取频道名称
            ipList: function(data, callback) {
                var url = PreSet.Constant.ipListUrl;

                $.ajax({
                    url: url,
                    type: 'get',
                    data: data,
                    dataType: 'json',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                });
            },

            //获取频道名称
            redirect: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options,'/redirect');
            }

        });
	}
);
define('../preSet/PreSet.Edit',['require','exports','module'],function(require, exports, module) {
    PreSet.Edit = function(options) {
        this.dao = PreSet.Dao;
        this.options = $.extend(true, {}, options);
        this.modify = Com.url.getQueryValue("modify",location.href);
        this.channel_id = Com.url.getQueryValue("channel_id",location.href);
        this.channel_name = Com.url.getQueryValue("channel_name",location.href);

        this.album_id = Com.url.getQueryValue("album_id",location.href) ? Com.url.getQueryValue("album_id",location.href) : "";
        this.album_name = Com.url.getQueryValue("album_name",location.href) ? Com.url.getQueryValue("album_name",location.href) : "";
        this.scale = Com.url.getQueryValue("scale",location.href) ? Com.url.getQueryValue("scale",location.href) : "";
        this.repeat_info = Com.url.getQueryValue("repeat_info",location.href) ? Com.url.getQueryValue("repeat_info",location.href) : "";
        this.start_time = Com.url.getQueryValue("start_time",location.href) ? Com.url.getQueryValue("start_time",location.href) : "";
        this.stop_time = Com.url.getQueryValue("stop_time",location.href) ? Com.url.getQueryValue("stop_time",location.href) : "";
        this.priority = Com.url.getQueryValue("priority",location.href) ? Com.url.getQueryValue("priority",location.href) : "0";
        this.util = PreSet.Util || {};
        this.construct = options.construct || function() {
            this.init();
        };
        this.config = $.extend({}, options.config);
        // 放在最下方立即执行f
        this.construct.call(this);
    };

    PreSet.Edit.prototype = {
        initConfig: function() {
			return true;
		},
        init: function() {
        },

        run: function() {
            var self = this;
            var $container = self.options.$container;
            this.init();
            self.initConfig();

			self.bindEvent();
            self.initSuggest();
            self.perpareData();
        },

        perpareData: function() {
            var self = this;
            $('#operate').val(self.modify);
            $('#channel_id').val(self.channel_id);

            $('input[name="thriftVideo.albumId"]').val(self.album_name);
            $('#album_id').val(self.album_id);
            $('#album_name').val(self.album_name);
            $('input[name="start_time"]').val(self.start_time);
            $('input[name="stop_time"]').val(self.stop_time);

            var repeat_info_array = self.repeat_info.split(',');
            var repeat_info_html = "";
            for(var i=1; i<8; i++) {
                var checked = "";
                for(var j=0; j<repeat_info_array.length; j++) {
                    if (i == repeat_info_array[j]) {
                        checked ="checked='checked'";
                        break;
                    }
                }
                repeat_info_html += "<label class='checkbox inline'><input type='checkbox' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
            }
            $('#repeat_info_div').html(repeat_info_html);

            var scale_html = "";
            for (var i=0; i<3; i++) {
                var checked = PreSet.Config.SCALE_VALUE[i]==self.scale ? "checked='checked'" : '';
                scale_html += "<label class='radio inline'> <input type='radio' name='scale' value='" + PreSet.Config.SCALE_VALUE[i] + "' " + checked + " >" + PreSet.Config.SCALE[i] + "</label>";
            }
            $('#scale_div').html(scale_html);

            var priority_html = "";
            for (var i=3; i>=0; i--) {
                var checked = PreSet.Config.PRIORITY_VALUE[i]==self.priority ? "checked='checked'" : '';
                priority_html += "<label class='radio inline'> <input type='radio' name='priority' value='" + PreSet.Config.PRIORITY_VALUE[i] + "' " + checked + " >" + PreSet.Config.PRIORITY[i] + "</label>";
            }
            $('#priority_div').html(priority_html);
        },
        bindEvent: function() {
            var self = this;

			jQuery.validator.addMethod("isValidTime", function(value, element, param) {

				var isValidTime = function(timeStr) {
										var date = '00:00:00';
										if (!timeStr || (timeStr.length < date.length) || ('string' !== typeof timeStr)) {
											return false;
										}
										try {
											var parts = (timeStr || '').split(':');
											if (parts.length > 3) {
												return false;
											}

											// var minute = parseInt(parts[0], 10);
											// var second = parseInt(parts[1], 10);
											var hour   = Number(parts[0]).toFixed(0);
											var minute = Number(parts[1]).toFixed(0);
											var second = Number(parts[2]).toFixed(0);

											if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)|| (parts[2].indexOf('.') != -1)) {
												return false;
											}
											if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
												return false;
											}
											if ((hour>=0 && hour<24) && (minute >= 0 && minute<60) && (second >= 0 && second < 60)) {
												return true;
											}
										} catch (e) {
											console.log(e.message);
										}
										return false;
									};

				return isValidTime(value);
			});


            var $container = self.options.$container;
            var $submit = $container.find('#Submit');
            var validator = self.getValidator();

			$form = $container;
			$form.find('input[name="start_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="start_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm:ss'
			});
			$form.find('input[name="stop_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="stop_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm:ss'
			});

            $submit.on('click', function() {
                var _save = function(data) {
                    $('#pageAlertValudError').hide();
                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });
                    self.save(data);
                };
				var success = validator.form();
                var data = self.getParam();

				if (success){
					_save(data);
				}

            });
        },
        initSuggest:function(){
            var self = this;
            var $container = self.options.$container;
            var type = 'properTitle';
            var tpl = '<div><div class="contract-item">{{html varCatalogStatusColor }}' +
                                '<span class="contract-width100">${entityId}</span>' +
                                '<span class="contract-width150">{{html displayName }}</span>' +
                                '<span class="contract-width150">{{html properTitle }}</span>' +
                                '<span class="contract-width80" >${channelName}</span>' +
                                '<span class="contract-width80" >${categoryName}</span>' +
                                '<span class="contract-width50">${totalNumberOfEpisodes}</span>' +
                                '<span class="contract-width100">${globalPublishDate}</span>' +
                                '</div></div>';
            var title = {
                            entityId: '专辑ID',
                            qipuId: '奇谱ID',
                            displayName: '专辑显示名(无多发)',
                            properTitle: '专辑原名(无多发)',
                            channelName: '所属频道',
                            categoryName: '主频道',
                            totalNumberOfEpisodes: '总集数',
                            globalPublishDate: '发行时间'
                        };
            var getHtmlByData = function(data) {
                                var htmls = [];
                                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                return htmlStr.html();
                            };
            var titleHtml = getHtmlByData(title);
            var albumIdSuggest = {
                options:{
                    source:"/api/redirect",
                    header: titleHtml,
                    method: "post",
                    multiple: false,
                    select: function(event, ui) {

                        if (ui && ui.item) {
                            $container.find('input[name="thriftVideo.albumId"]').attr('data-displayName', ui.item.properTitle);
                            $container.find('input[name="thriftVideo.albumId"]').attr('data-channel-id', ui.item.channel);
                            $container.find('input[name="ablum_id"]').val(ui.item.id);
                            $container.find('input[name="ablum_name"]').val(ui.item.properTitle.replace(/<b>|<\/b>/g,""));
                        }
                    },
                    parseValue: function() {
                        var val = this.element.val();
                        var ret = [];
                        if (val) {
                            var items = val.split(';');
                            $.each(items, function(i, item) {
                                item = item.split(',');
                                ret.push({
                                    value: item[1],
                                    id: item[0],
                                    label: item[1]
                                });
                            });
                        }
                        this._value('');
                        return ret;
                    },
                    getParam: function (term) {
                        var params = term.length == 0 ? {type:"properTitle", filter_EQI_isMainChannel:1}:{type:"properTitle", filter_EQI_isMainChannel:1, word: term};
                        var requestData = {url:  "http://lego.iqiyi.com/suggest/album", type: "get", params:params , needCookie: false};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },

                    process: function(json) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, {
                                value: item[type]
                            }, item, {
                                // displayName: item[type],
                                id: item.entityId
                            }));
                        });
                        return ret;
                    },

                    template: function (item) {
                        return getHtmlByData(item);
                    }
                }
            };
            $("input[name='thriftVideo.albumId']").suggest(albumIdSuggest.options);
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, PreSet.Config.validator);

            return validator;
        },

        getParam: function() {
            var $container = this.options.$container;
            var self = this;
			var checkboxObj = null;
            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {
				if($(item).attr("name") != "thriftVideo.albumId")
				{
					return true;
				}
				return false;
            });

			var checkboxVal = [];
            var name;
            var key;
			var params = {};

            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name=='repeat_info') {
                        if(this.checked)
                        {
                            checkboxVal.push($(this).val());
                        }
                    } else if(name=="scale") {
                        if(this.checked)
                        {
                            params[name] = $(this).val();
                        }
                    } else if(name=="priority") {
                         if(this.checked)
                         {
                             params[name] = $(this).val();
                         }
                    } else {
                        params[name] = $(this).val();
                    }
                }
            });

			if(checkboxVal.length!==0){
                params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
            }
            return params;
        },
        save: function(data) {
            var request = {};
            request.url='http://lego.iqiyi.com/live2VOD/preSet/save';
            request.type='post';
            request.params = data;
            request.needCookie = {};
            var requestJson = JSON.stringify(request);

            this.dao.redirect({request:JSON.stringify(request)}, this.onSave);
        },
        onSave: function(json) {
            if (json.code == '200') {
                var url = '/epg/live2VOD_preset_home.html?channel_name='+Com.url.getQueryValue("channel_name",location.href)+'&channel_id='+Com.url.getQueryValue("channel_id",location.href);

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);
                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {
                $(document).tips({
                    content: json.msg,
                    type: "error"
                });
            }

        }

    };

});

define(
    '../preSet/PreSet.Grid',['require','exports','module'],function(require, exports, module) {


        PreSet.Grid = function(options) {
            this.dao = PreSet.Dao;
            this.config = PreSet.Config;
            this.options = options || {};
			this.channel_id = Com.url.getQueryValue("channel_id",location.href);
			this.channel_name = Com.url.getQueryValue("channel_name",location.href);
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);

        };

        Com.inherits(PreSet.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
                self.initSuggest();
            },
            perpareData: function() {
                //var request = {};
                //request.url=PreSet.Constant.ipListUrl;
                //request.type='get';
                //request.params = {'type':0,'area':0,'from_client':'true'};
                //request.needCookie = {};
                //var requestJson = JSON.stringify(request);

                //this.dao.redirect({request:request}, function(data){
                //    $('#ipList').attr("ipList") = data;
                //});
                this.dao.ipList({'type':0,'area':0,'from_client':'true'}, function(data){
                    $('#ipList').attr("ipList", JSON.stringify(data));
                });
                //$("#env").attr("env") = PreSet.Constant.preRecocordUrl;
            },

            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

                $form.find('.query-add').click(function() {
					window.open("/epg/live2VOD_preset_edit.html?modify=add&channel_id="+self.channel_id+"&channel_name="+self.channel_name);
                });

				var regionList = ['cq','sh','bj'];

                $form.find('.pre-input').click(function() {
					var ipObj = JSON.parse($('#ipList').attr("ipList")),
						options = '';

					if(ipObj.code==200)
					{
						$.each(ipObj.response.list,function(i,v){
							options +='<option value="'+v[0]+'" >'+v[0]+'['+regionList[v[1]]+']</option>';
						});
					}

					var html = '<div style="text-align:center;"><h3 style="margin-left:-170px;">请选择导入的频道信息</h3><div class="row">服务器ip:<select id="dst_ip">'
					+options+'</select></div><div class="row">频道代号:<input type="text" name="channel_code"/></div><div  class="controls"><button type="button" class="btn btn-primary pre_confirm">确定</button>&nbsp;<button type="submit"  class="btn btn-primary pre_cancel">取消</button></div></div>';
					$(html).dialog({
						/* title : title,*/
						width: 300,
						height: 200,
						modal: true,
						appendTo: $container,
						close: function() {
						}
					});

					$(".pre_cancel").unbind("click").bind("click",function(){
						$(".ui-dialog-titlebar-close").trigger("click");
					});

					$(".pre_confirm").unbind("click").bind("click",function(){

						self.dao.saveAssociation({'channel_id':self.channel_id,'dst_channel_ip':$("#dst_ip").val(),'dst_channel_code':$('[name="channel_code"]').val()}, function(data){
							if(data.response.status === 0)
							{
								$(document).tips({
									content: "关联成功",
									type: "success"
								});

								setTimeout("window.location.reload()",1000);
								$(".ui-dialog-titlebar-close").trigger("click");
							}
							else
							{
								$(document).tips({
									content: data.response.error,
									type: "error"
								});
							}

						});
					});

                });

				$container.find('input[name="thriftVideo.albumId"]').blur(function(){
					if($(this).val()==="")
					{
						$container.find('input[name="ablum_id"]').val("");
						$container.find('input[name="ablum_name"]').val("");
					}
				});

				$("[type=reset]").click(function(){
					$container.find('input[name="ablum_id"]').val("");
					$container.find('input[name="ablum_name"]').val("");
				});

			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="start_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="start_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm:ss'
                });
                $form.find('input[name="stop_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="stop_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm:ss'
                });
                //Suggest.Action.channel($form.find('input[name=channeltype]'), {
                //    isFgtw: User.Util.isPartner() ? true : false
                //});

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();

                self.echoQuery();

                options = $.extend(true, {
                    width: 1700,
                   // multiselect: true,
                    multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
                self.loadTableByDate();
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {"channel_id":self.channel_id};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					if($(item).attr("name") != "thriftVideo.albumId")
					{
						return true;
					}
					return false;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')
						{   /*
							if(params[name]==undefined)
							{
								params[name] = [];
							}
							*/
							if(this.checked)
							{
								checkboxVal.push($(this).val());
							}
						}
						else if(name=="scale")
						{
							if(this.checked)
							{
								params[name] = $(this).val();
							}
						}
						else
						{
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },
            loadTableByDate:function(){
                var self = this;
                self.$grid.setGridParam({page: 1, url:'/api/redirect' , loadtext: '加载中...',
                    datatype:"json",
                    loadui: "block",
                    postData:{"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:{channel_id: self.channel_id} , needCookie: false})}
                    }).trigger("reloadGrid");
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:params , needCookie: false})}
                }).trigger('reloadGrid');
            },
            initSuggest:function(){
                var self = this;
                var $container = self.options.$container;
                var type = 'properTitle';
                var tpl = '<div><div class="contract-item">{{html varCatalogStatusColor }}' +
                                    '<span class="contract-width100">${entityId}</span>' +
                                    '<span class="contract-width150">{{html displayName }}</span>' +
                                    '<span class="contract-width150">{{html properTitle }}</span>' +
                                    '<span class="contract-width80" >${channelName}</span>' +
                                    '<span class="contract-width80" >${categoryName}</span>' +
                                    '<span class="contract-width50">${totalNumberOfEpisodes}</span>' +
                                    '<span class="contract-width100">${globalPublishDate}</span>' +
                                    '</div></div>';
                var title = {
                                entityId: '专辑ID',
                                qipuId: '奇谱ID',
                                displayName: '专辑显示名(无多发)',
                                properTitle: '专辑原名(无多发)',
                                channelName: '所属频道',
                                categoryName: '主频道',
                                totalNumberOfEpisodes: '总集数',
                                globalPublishDate: '发行时间'
                            };
                var getHtmlByData = function(data) {
                                    var htmls = [];
                                    var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                    return htmlStr.html();
                                };
                var titleHtml = getHtmlByData(title);
                var albumIdSuggest = {
                    options:{
                        source:"/api/redirect",
                        header: titleHtml,
                        method: "post",
                        multiple: false,
                        select: function(event, ui) {

                            if (ui && ui.item) {
                                $container.find('input[name="thriftVideo.albumId"]').attr('data-displayName', ui.item.properTitle);
                                $container.find('input[name="thriftVideo.albumId"]').attr('data-channel-id', ui.item.channel);
                                $container.find('input[name="ablum_id"]').val(ui.item.id);
                                $container.find('input[name="ablum_name"]').val(ui.item.properTitle.replace(/<b>|<\/b>/g,""));
                            }
                        },
                        parseValue: function() {
                            var val = this.element.val();
                            var ret = [];
                            if (val) {
                                var items = val.split(';');
                                $.each(items, function(i, item) {
                                    item = item.split(',');
                                    ret.push({
                                        value: item[1],
                                        id: item[0],
                                        label: item[1]
                                    });
                                });
                            }
                            this._value('');
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {type:"properTitle", filter_EQI_isMainChannel:1}:{type:"properTitle", filter_EQI_isMainChannel:1, word: term};
                            var requestData = {url:  "http://lego.iqiyi.com/suggest/album", type: "get", params:params , needCookie: false};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function(json) {
                            var data = json.data;
                            if (!data) {
                                return [];
                            }
                            var ret = [];
                            $.map(data, function(item) {
                                ret.push($.extend(true, {
                                    value: item[type]
                                }, item, {
                                    // displayName: item[type],
                                    id: item.entityId
                                }));
                            });
                            return ret;
                        },

                        template: function (item) {
                            return getHtmlByData(item);
                        }
                    }
                };
                $("input[name='thriftVideo.albumId']").suggest(albumIdSuggest.options);
            },
			del : function(channel_id,ablum_id){
                var self = this;

                if(window.confirm('是否确认删除该专辑信息？')){
                    var request = {};
                    request.url='http://lego.iqiyi.com/live2VOD/preSet/del';
                    request.type='get';
                    request.params = {'channel_id':channel_id,'ablum_id':ablum_id};
                    request.needCookie = {};
                    var requestJson = JSON.stringify(request);

                    this.dao.redirect({request:JSON.stringify(request)}, function(){self.query();});
                    return true;
                }
            }


        });

    }
);
define('../preSet/PreSet.Util',['require','exports','module'],function(require, exports, module) {
	PreSet.Util = $.extend(true, {}, Ancestor.Util, {
			formatter: {
				score : function(v,r)
				{
					var score = parseFloat(r.score,10);

					if(!isNaN(score) && score!==0){
						return score;
					}
					else{
						return "/";
					}
				},
				avgScore : function(v,r)
				{
					var score = parseFloat(r.avg_score,10);

					if(!isNaN(score) && score!==0){
						return score;
					}
					else{
						return "/";
					}
				},
				repeatInfo:function(v,r)
				{
					var str = "";
					for(var i in r.repeat_info)
					{
						str += PreSet.Config.REPEAT_INFO[r.repeat_info[i]-1]+',';
					}

					return str.substr(0,str.length-1);
				},
				scale:function(v,r)
				{
					var str = "";
					if(r.scale===""){
						str = PreSet.Config.SCALE[0];
					}
					else if(r.scale=="16x9"){
						str = PreSet.Config.SCALE[1];
					}
					else if(r.scale=="4x3"){
						str = PreSet.Config.SCALE[2];
					}
					return str;
				},
				priority:function(v,r)
				{
					return PreSet.Config.PRIORITY[r.priority];
				},
				videoHead : function(v,r)
				{   if(r.headImg!="none" && r.headImg!==undefined){
						return '<a target="_blank" href="http://lego.iqiyi.com/live2VOD/preSet/advertisementLibrary?type=headimage&channel_name='+r.ablum_name+'&channel_id='+r.channel_id+'&ablum_id='+r.ablum_id+'"><img src="'+r.headImg+'" /></a>';
					}
					else
					{
						return "无";
					}
				},
				videoTail : function(v,r)
				{
					if(r.tailImg!="none" && r.tailImg!==undefined){
						return '<a target="_blank" href="http://lego.iqiyi.com/live2VOD/preSet/advertisementLibrary?type=tailimage&channel_name='+r.ablum_name+'&channel_id='+r.channel_id+'&ablum_id='+r.ablum_id+'"><img src="'+r.tailImg+'" /></a>';
					}
					else
					{
						return "无";
					}
				},
				adLibary : function(v,r)
				{
					r.adsImageNumber = parseInt(r.adsImageNumber,10);
					if(r.adsImageNumber !==0 && !isNaN(r.adsImageNumber))
					{
						return '<a target="_blank" href="http://lego.iqiyi.com/live2VOD/preSet/advertisementLibrary?type=adsimage&channel_name='+r.ablum_name+'&channel_id='+r.channel_id+'&ablum_id='+r.ablum_id+'">'+r.adsImageNumber+'</a>';
					}
					else
					{
						return '无';
					}
				},
				operate:function(v,r){
					return "<a href='/epg/live2VOD_preset_edit.html?modify=edit&channel_id="
					+r.channel_id+"&channel_name="+Com.url.getQueryValue("channel_name",location.href)
					+"&album_id="+r.ablum_id+"&album_name="+r.ablum_name+"&scale="+r.scale+"&repeat_info="+r.repeat_info
					+"&start_time="+r.start_time+"&stop_time="+r.stop_time+"&priority="+r.priority
					+"' target='_blank'>修改</a> | <a href='javascript:;' title='删除' onclick='PreSet.Action.getPreSetGrid().del("
					+ r.channel_id +","+r.ablum_id+");'>删除</a>";
				}
			},
			preSetDel : function(options) {

			}
		});
});
define(
	'../news/News',['require','exports','module'],function(require, exports, module){
		window.News = window.News || { version : '1.0' };
		//Video公共配置集合，键值对象
		News.Config = News.Config || {};
		News.Util = News.Util || {};

        News.Constant = {
            baseApiUrl:(auth.dev() ? "http://10.23.70.33:7000/":"http://dot.live.qiyi.domain/"),
            newsApiUrl:(auth.dev() ? "http://10.23.70.33:7008/":"http://dispatch.live2vod.qiyi.domain:7008/"),
            devMode: auth.dev()
        }

        News.urlConfig = (function () {
            var useUrl = News.Constant.baseApiUrl;
            var modify = useUrl+"v1/channel/modify";
            var channel = useUrl+"v1/channel";
            var machinelist= useUrl+"v1/channel/machinelist";
            var machinemodify = useUrl + "v1/channel/machinemodify";
            var newsApiUrl = News.Constant.newsApiUrl;
            var news = newsApiUrl + "v1/shortablum";
            var newsModify = newsApiUrl + "v1/shortablum/modify";
            return {
                modifyUrl:modify,
                machinemodifyUrl:machinemodify,
                channelUrl:channel,
                machinelistUrl:machinelist,
                newsUrl:news,
                newsModifyUrl:newsModify
            }
        })()
	}
);
define(
	'../news/News.Action',['require','exports','module'],function(require, exports, module){

        News.Action = (function() {
			var newsGrid = null;
            var getNewsGrid = function(options) {
                if (!newsGrid) {

                    newsGrid = new News.Grid($.extend(true, {
                        '$container': $('#NewsListContainer'),
                        type: 0
                    }, options));
                }
                return newsGrid;
            };
            var newsGridRun = function(options) {
                newsGrid = getNewsGrid(options);
                newsGrid.run();
            };
			var run = function() {
                /* videoQueryRun();*/
                newsGridRun({});
            };
            var editBase = null;
            var getEditBase = function(options) {

                if (!editBase) {
                    editBase = new News.Edit(options);
                }
                return editBase;
            };
            var editRun = function() {
                var $container = $('.video-edit-form');
                getEditBase({
                    $container: $container
                }).run();
            };
            return {
                run: run,
				editRun:editRun,
				getNewsGrid:getNewsGrid
            };
        })();
	}
);
define('../news/News.Config',['require','exports','module'],function(require, exports, module) {

    News.Config = {

		REPEAT_INFO : ["周一","周二","周三","周四","周五","周六","周日"], //播放日期
        REGION_LIST: ['cq', 'sh', 'bj'],
        REGION_CH_LIST: ['重庆', '上海', '北京'],
        NEWS_STATUS: ['等待开播', '正在拆条', '拆条完成'],
        IP_LINK_AREA: {},
        IP_LINK_CH_AREA: {},
        PageBean: null,

        queryValidator: {
            messages: {
                start_time: {
                    isValidTime: "节目开始时间格式错误，格式应为：12:00",
                },
                stop_time: {
                    isValidTime: "节目结束时间格式错误，格式应为：12:00"
                }
            },
            rules: {
                start_time: {
                    isValidTime: true,
                },
                stop_time: {
                    isValidTime: true
                }
            }
        },

        validator: {
            messages: {
                program_name: {
                    required: "新闻节目名称不能为空",
                },
                channel_name: {
                    required: '所属电视台不能为空',
                },
                start_time: {
                    required: '节目开始时间不能为空',
                    isValidTime: "节目开始时间格式错误，格式应为：12:00",
                },
                stop_time: {
                    required: '节目结束时间不能为空',
                    isValidTime: "节目结束时间格式错误，格式应为：12:00",
                },
                repeat_info: '请至少选择一个播放日期',
            },
            rules: {
                program_name: {
                    required: true,
                },
                channel_name: {
                    required: true,
                },
                start_time: {
                    required: true,
                    isValidTime: true,
                },
                stop_time: {
                    required: true,
                    isValidTime: true,
                },
                repeat_info: {
                    minlength: 1,
                },
            }
        },

			TABLE_COLMODEL_CONFIG: {
				'program_name': {
					name: 'program_name',
					title: false,
					index: 'program_name',
					align:'center',
					sortable: false,
					width: 140
				},
				'channel_name': {
                    name: 'channel_name',
                    title: false,
                    index: 'channel_name',
                    align:'center',
                    sortable: false,
                    width: 140
                },
                'channel_area': {
                    name: 'channel_area',
                    title: false,
                    index: 'channel_area',
                    align:'center',
                    sortable: false,
                    width: 140,
                    formatter: function(v, o, r) {
                        return News.Util.formatter.channelArea(v,r);
                    }
                },
                'channel_ip': {
                    name: 'channel_ip',
                    title: false,
                    index: 'channel_ip',
                    align:'center',
                    sortable: false,
                    width: 140
                },
				'repeat_info': {
					name: 'repeat_info',
					title: false,
					index: 'repeat_info',
					align:'center',
					width: 230,
					sortable: false,
					formatter: function(v, o, r) {
						return News.Util.formatter.repeatInfo(v,r);
					}
				},
				'start_time': {
					name: 'start_time',
					title: false,
					index: 'start_time',
					align:'center',
					sortable: false,
					width: 100,
					align: 'center',
                    formatter: function(v, o, r) {
                        return News.Util.formatter.startTime(v,r);
                    }
				},
				'stop_time': {
					name: 'stop_time',
					title: false,
					index: 'stop_time',
					align:'center',
					width: 100,
					sortable: false,
					align: 'center',
					formatter: function(v, o, r) {
                        return News.Util.formatter.stopTime(v,r);
                    }
				},
				'status': {
					name: 'status',
					title: false,
					index: 'status',
					align:'center',
					sortable: false,
					width: 250,
					formatter: function(v, o, r) {
						return News.Util.formatter.status(v,r);
					}
				},
				'operate': {
					name: 'operate',
					title: false,
					index: 'operate',
					width: 140,
					align:'center',
					sortable: false,
					formatter: function(v, o, r) {
						return News.Util.formatter.operate(v,r);
					}

				},
				'statistics_show': {
				    name: 'statistic_show',
				    title: false,
				    index: 'statistics',
				    width: '100',
				    align: 'center',
				    sortable: false,
				    formatter: function(v, o, r) {
				        return News.Util.formatter.statisticsShow(v,r);
				    }
				}

			},

			TABLE: {
			    localReader: {
                    id: "program_id",
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records"
                },
			    url: News.urlConfig.newsUrl,
			    datatype: "local",
			    loadtext: '加载中...',
                loadui: "block",
                mtype: "get",
                rowNum: 10,
                pager: "#NewsListPager",
                multiselect: false,
                onPaging: function(pgButton) {
                    var retValue = null;
                    retValue = News.Util.pageBeanPageHandler("NewsListGrid", "NewsListPager" , News.Config.PageBean ,pgButton);
                    if (retValue != null) {
                        $("#NewsListGrid")[0].addJSONData(retValue);
                    }
                    return "stop";
                },
				//colNames: ["新闻节目名称", "所属电视台", "服务器", "服务器IP", "播出日期", "起始时间", "结束时间", "当前状态", "操作","准确率查询"],
				colNames: ["新闻节目名称", "所属电视台", "服务器", "服务器IP", "播出日期", "起始时间", "结束时间", "当前状态","操作"],
				//colModel: ['program_name', 'channel_name', 'channel_area', 'channel_ip', 'repeat_info', 'start_time', 'stop_time', 'status', 'operate', 'statistics_show']
				colModel: ['program_name', 'channel_name', 'channel_area', 'channel_ip', 'repeat_info', 'start_time', 'stop_time', 'status', 'operate']
			}
		};
});
define(
	'../news/News.Dao',['require','exports','module'],function(require, exports, module){

        News.Dao = $.extend({}, Ancestor.Dao, {
            getList: function (data, callback) {
                var options = {
                    type: "get",
                    url: News.urlConfig.newsUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            add: function (data, callback) {
                var options = {
                    type: "post",
                    url: News.urlConfig.newsUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            modify: function (data, callback) {
                var options = {
                    type: "post",
                    url: News.urlConfig.newsModifyUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            redirect: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options,'/redirect');
            }

        });
	}
);
define('../news/News.Edit',['require','exports','module'],function(require, exports, module) {
    News.Edit = function(options) {
        this.dao = News.Dao;
        this.options = $.extend(true, {}, options);
        this.modify = Com.url.getQueryValue("modify",location.href);

        this.util = News.Util || {};
        this.config = News.config || {};
        this.construct = options.construct || function() {
            this.init();
        };
        this.config = $.extend({}, options.config);
        // 放在最下方立即执行
        this.construct.call(this);
    };

    News.Edit.prototype = {
        initConfig: function() {
			return true;
		},
        init: function() {
        },

        run: function() {
            var self = this;
            var $container = self.options.$container;
            self.init();
            self.initConfig();

			self.bindEvent();
			self.perpareData();
            self.initSuggest();
            self.fillForm();
        },

        perpareData: function() {
            var self = this;
            var username = $("div.user a.name").html();
            var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                              };
            self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                var hasDataRegion = [];

                if (data != null && data.response != null && data.response.list) {
                    $.each(data.response.list, function (index, obj) {
                        if (obj[1] >= 0 && obj[1] <= 2) {
                            if (hasDataRegion.indexOf(obj[1]) == -1) {
                                hasDataRegion.push(obj[1]);
                            }

                            News.Config.IP_LINK_AREA[obj[0]] = obj[1];
                            News.Config.IP_LINK_CH_AREA[obj[0]] = News.Config.REGION_CH_LIST[obj[1]]
                        }
                    });
                } else {
                    console.log("wait to do");
                }
            });
        },

        fillForm: function () {
            var programId = News.Util.getUrlId("programId");
            var self = this;
            if (programId != null) {
                self.dao.getList({program_id: programId}, function (data) {
                    var retValue = null;
                    if (data.code === 200 && data.response != null && data.response.list != null) {
                        retValue = data.response.list;
                        self.fillData(retValue[0]);
                    } else {
                        self.fillNoData();
                    }
                });
            } else {
                self.fillNoData();
            }
        },

        fillData: function (element) {
            var self = this;
            for (var key in element) {
                if (key == "repeat_info") {
                    var repeat_info_html = "";
                    var repeat_info_array = element[key];
                    for(var i=1; i<8; i++) {
                        var checked = "";
                        for(var j=0; j<repeat_info_array.length; j++) {
                            if (i == repeat_info_array[j]) {
                                checked ="checked='checked'";
                                break;
                            }
                        }
                        repeat_info_html += "<label class='checkbox inline'><input type='checkbox' id='repeat_info' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
                    }
                    $('#repeat_info_div').html(repeat_info_html);
                } else {
                    self.options.$container.find("input[name=" + key + "]").val(element[key]);
                }
            }
        },
        fillNoData: function () {
            var self = this;
            var repeat_info_html = "";
            for(var i=1; i<8; i++) {
                var checked = "";
                repeat_info_html += "<label class='checkbox inline'><input type='checkbox' name='repeat_info' value='" + i + "' " + checked + ">" + PreSet.Config.REPEAT_INFO[i-1] + "</label>";
            }
            $('#repeat_info_div').html(repeat_info_html);
        },

        bindEvent: function() {
            var self = this;

			jQuery.validator.addMethod("isValidTime", function(value, element, param) {
				var isValidTime = function(timeStr) {
                    var date = '00:00';
                    var formatTime = /^(\d{2}):(\d{2})$/
                    if (!timeStr || (timeStr.length < date.length) || ('string' !== typeof timeStr) || !formatTime.test(timeStr)) {
                        return false;
                    }
                    try {
                        var parts = (timeStr || '').split(':');
                        if (parts.length > 2) {
                            return false;
                        }

                        var hour   = Number(parts[0]).toFixed(0);
                        var minute = Number(parts[1]).toFixed(0);

                        if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)) {
                            return false;
                        }
                        if (isNaN(hour) || isNaN(minute)) {
                            return false;
                        }
                        if ((hour>=0 && hour<24) && (minute >= 0 && minute<60)) {
                            return true;
                        }
                    } catch (e) {
                        console.log(e.message);
                    }
                    return false;
                };

				return isValidTime(value);
			});

            var $container = self.options.$container;
            var $submit = $container.find('#Submit');
            var validator = self.getValidator();

			$form = $container;
			$form.find('input[name="start_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="start_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm'
			});
			$form.find('input[name="stop_time"]').timepicker({
				onClose: function(selectedDate) {
					$form.find('input[name="stop_time"]').timepicker("option", selectedDate);
				},
				timeFormat: 'HH:mm'
			});
            $submit.on('click', function() {
                var _save = function(data) {
                    if (data.channel_id == "") {
                        $(document).tips({
                            content: "请在Suggest中选择所属电视台",
                            type: "error"
                        });
                        return;
                    }
                    if (typeof(data.repeat_info) == "undefined") {
                        $(document).tips({
                            content: "请至少选择一个播放日期",
                            type: "error"
                        });
                        return;
                    }
                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });
                    if (data.program_id) {
                        self.edit(data);
                    } else {
                        self.add(data);
                    }
                };
				var success = validator.form();
                var data = self.getParam();

				if (success){
					_save(data);
				}

            });
        },
        initSuggest:function(){
            var self = this;
            var $container = self.options.$container;
            var type = 'properTitle';
            var tpl = '<div><div class="contract-item">' +
                                '<span class="contract-width100">${channel_name}</span>' +
                                '<span class="contract-width100">${channel_code}</span>' +
                                '<span class="contract-width80" >${server_region}</span>' +
                                '<span class="contract-width200">${channel_addr}</span>' +
                                '<span class="contract-width100">${channel_ip}</span>' +
                                '<span class="contract-width80" >${channel_status}</span>' +
                                '<span class="contract-width80" >${channel_type}</span>' +
                                '</div></div>';
            var title = {
                            channel_name: '所属电视台',
                            channel_code: '代号',
                            server_region: '服务器',
                            channel_addr: '流地址',
                            channel_ip: '服务器IP',
                            channel_status: '收录状态',
                            channel_type: '收费'
                        };
            var getHtmlByData = function(data) {
                                var htmls = [];
                                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                return htmlStr.html();
                            };
            var titleHtml = getHtmlByData(title);
            var channelNameSuggest = {
                options:{
                    source:News.urlConfig.channelUrl,
                    header: titleHtml,
                    method: "get",
                    multiple: false,
                    validate: true,
                    clearInvalid: true,
                    noResult: '对不起，没有这个结果',
                    onblur: function() {
                        console.log('onblur');
                    },
                    onNoResult: function() {
                        console.log('noResult');
                    },
                    select: function(event, ui) {
                        if (ui && ui.item) {
                            $container.find('input[name="channel_code"]').val(ui.item.channel_code);
                            $container.find('input[name="channel_area"]').val(ui.item.channel_area);
                            $container.find('input[name="channel_ip"]').val(ui.item.channel_ip);
                            $container.find('input[name="channel_id"]').val(ui.item.channel_id);
                        }
                    },
                    parseValue: function() {
                        var val = this.element.val();
                        var ret = [];
                        if (val) {
                            var items = val.split(';');
                            $.each(items, function(i, item) {
                                item = item.split(',');
                                ret.push({
                                    value: item[1],
                                    id: item[0],
                                    label: item[1]
                                });
                            });
                        }
                        this._value('');
                        return ret;
                    },
                    getParam: function (term) {
                        var requestData = {type:0, from_client:true, channel_name: term, _: new Date().getTime()};
                        return requestData;
                    },

                    process: function(json) {
                        var data = json.response.list;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, {
                                value: item.channel_name
                            }, item, {
                                // displayName: item[type],
                                id: item.channel_id,
                                channel_status: News.Util.formatter.channel_status(item.channel_status),
                                channel_type: News.Util.formatter.freeType(item.freeType),
                                channel_area: News.Config.IP_LINK_AREA[item.channel_ip],
                                server_region: News.Config.IP_LINK_CH_AREA[item.channel_ip]
                            }));
                        });
                        return ret;
                    },

                    template: function (item) {

                        return getHtmlByData(item);
                    }
                }
            };
            $("input[name='channel_name']").suggest(channelNameSuggest.options);
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, News.Config.validator);

            return validator;
        },

        getParam: function() {
            var $container = this.options.$container;
            var self = this;
			var checkboxObj = null;
            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {

				return true;
            });

			var checkboxVal = [];
            var name;
            var key;
			var params = {};

            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name=='repeat_info') {
                        if(this.checked)
                        {
                            checkboxVal.push($(this).val());
                        }
                    } else if(name=='program_id' && $(this).val() == "") {

                    } else {
                        params[name] = $(this).val();
                    }
                }
            });

			if(checkboxVal.length!==0){
                params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
            }
            return params;
        },
        add: function(data) {
            this.dao.add(data, this.onSave);
        },
        edit: function(data) {
            var params = $.extend(true, {func : "modify_ablum"}, data);
            this.dao.modify(params, this.onSave);
        },

        onSave: function(json) {
            if (json.code == '200' && json.response.status == 0) {
                var url = '/epg/news_home.html';

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);
                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {
                $(document).tips({
                    content: json.response.error,
                    type: "error"
                });
            }

        },

    };

});

define(
    '../news/News.Grid',['require','exports','module'],function(require, exports, module) {

        News.Grid = function(options) {
            this.dao = News.Dao;
            this.config = News.Config;
            this.util = News.Util;
            this.options = options || {};
			//this.channel_id = Com.url.getQueryValue("channel_id",location.href);
			//this.channel_name = Com.url.getQueryValue("channel_name",location.href);
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);
        };

        Com.inherits(News.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
                //self.initSuggest();
            },

            perpareData: function() {
                var self = this;
                var username = $("div.user a.name").html();
                var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                    params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                  };
                self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                    var parentJDom = $("select[name=channel_area]");
                    var hasDataRegion = [];

                    $("<option>", {value: "all", html: "全部"}).appendTo(parentJDom);

                    if (data != null && data.response != null && data.response.list) {
                        $.each(data.response.list, function (index, obj) {
                            if (obj[1] >= 0 && obj[1] <= 2) {
                                if (hasDataRegion.indexOf(obj[1]) == -1) {
                                    hasDataRegion.push(obj[1]);
                                }

                                News.Config.IP_LINK_AREA[obj[0]] = obj[0] + "[" + News.Config.REGION_LIST[obj[1]] + "]";
                            }
                        });
                        $.each(hasDataRegion, function (i, element) {
                            $("<option>", {
                                value: element,
                                html: News.Config.REGION_CH_LIST[element]
                            }).appendTo(parentJDom);
                        })
                    } else {
                        console.log("wait to do");
                    }
                });
            },

            bindBasicEvent: function() {
                var self = this;
                jQuery.validator.addMethod("isValidTime", function(value, element, param) {
                    var isValidTime = function(timeStr) {
                        var date = '00:00';
                        var formatTime = /^(\d{2}):(\d{2})$/
                        if (!timeStr || timeStr == "") {
                            return true;
                        }
                        if ((timeStr.length < date.length) || ('string' !== typeof timeStr) || !formatTime.test(timeStr)) {
                            return false;
                        }
                        try {
                            var parts = (timeStr || '').split(':');
                            if (parts.length > 2) {
                                return false;
                            }

                            var hour   = Number(parts[0]).toFixed(0);
                            var minute = Number(parts[1]).toFixed(0);

                            if ((parts[0].indexOf('.') != -1) || (parts[1].indexOf('.') != -1)) {
                                return false;
                            }
                            if (isNaN(hour) || isNaN(minute)) {
                                return false;
                            }
                            if ((hour>=0 && hour<24) && (minute >= 0 && minute<60)) {
                                return true;
                            }
                        } catch (e) {
                            console.log(e.message);
                        }
                        return false;
                    };

                    return isValidTime(value);
                });

                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

                $form.find('.query-add').click(function() {
					window.open("/epg/news_edit.html");
                });

                $form.find('#news-details').click(function() {
                    window.open("/epg/news_details.html");
                });

                $form.find('#news-statistic').click(function() {
                    window.open("/epg/news_statistic.html");
                });

				$("[type=reset]").click(function(){
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=channel_area]").change();
				});

                $("select[name=channel_area]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var username = $("div.user a.name").html();
                    var requestData = {url: News.urlConfig.machinelistUrl, type: "get",
                                                        params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                      };

                    self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function(data) {
                        var responseData = data;
                        var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                        if (responseData != null && responseData.response != null && responseData.response.list != null) {
                            $.each(responseData.response.list, function (i, obj) {
                                if ((eqVal == null && obj[1] >= 0 && obj[1] <= 2) || eqVal == obj[1]) {
                                    $("<option>", {
                                        value: obj[0],
                                        html: News.Config.IP_LINK_AREA[obj[0]]
                                    }).appendTo(selectJDom);
                                }
                            })
                        }
                    });

                });
                $("select[name=channel_area]").change();
			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="start_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="start_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm'
                });
                $form.find('input[name="stop_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="stop_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm'
                });

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();
                options = $.extend(true, {
                    width: 1700,
                   // multiselect: true,
                    //multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.$grid.jqGrid(options);

              //  self.initGrid.call(this, options, callback);
                //TODO self.loadTableByDate();
                 self.echoQuery();
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return true;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')	{
							if(this.checked){
								checkboxVal.push($(this).val());
							}
						} else if ((name=='channel_area' && $(this).val()=='all') || (name=='channel_ip' && $(this).val()=='all')){
						} else {
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },
            loadTableByDate:function(){
                var self = this;
                self.$grid.setGridParam({page: 1, url:'/api/redirect' , loadtext: '加载中...',
                    datatype:"json",
                    loadui: "block",
                    postData:{"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:{channel_id: self.channel_id} , needCookie: false})}
                    }).trigger("reloadGrid");
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                var validator = self.getValidator();
                var success = validator.form();
                if (success) {
                    self.config.PageBean = EpgWeb.Util.createPageBean();
                    self.dao.getList(params, function (data) {
                         var retValue = null;
                         if (data.code === 200 && data.response != null && data.response.list != null) {
                             self.config.PageBean.setNewData(data.response.list);
                         } else {
                             self.config.PageBean.setNewData([]);
                         }
                         retValue = self.config.PageBean.getCur();
                         self.$grid[0].addJSONData(retValue);
                         self.showNoData(self.$grid);
                     });
                 }
            },
            getValidator: function() {
                var $form = $("form[name='basicFrm']");
                var validator = Validator.getValidator($form, News.Config.queryValidator);

                return validator;
            },
            showNoData: function (jqGridTarget) {
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            }

        });

    }
);
define('../news/News.Util',['require','exports','module'],function(require, exports, module) {
	News.Util = $.extend(true, {}, EpgWeb.Util, {
			formatter: {
			    channel_status: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "收录中"
                    } else if (cellvalue == null) {
                        return "错误";
                    }
                    return "未收录";
                },
                freeType: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "是"
                    }
                    return "否"
                },
                channel_ip: function (cellvalue, options, rowObject) {
                    if (cellvalue == null || News.Config.IP_LINK_AREA[cellvalue] == null) {
                        return "未知"
                    }
                    return News.Config.IP_LINK_AREA[cellvalue]
                },
                repeatInfo:function(v,r) {
                    var str = "";
                    for(var i in r.repeat_info)
                    {
                        str += News.Config.REPEAT_INFO[r.repeat_info[i]-1]+',';
                    }

                    return str.substr(0,str.length-1);
                },
                channelArea:function(v,r) {
                    return News.Config.REGION_CH_LIST[v];
                },
                startTime:function(v,r) {
                    return v;
                },
                stopTime:function(v,r) {
                    return v;
                },
                status:function(v,r) {
                    var str = "当前有" + r.count + "条待审核";
                    var startTime = r.start_time.split(":");
                    var startHours = startTime[0];
                    var startMinutes = startTime[1];
                    var startMinutesTime = parseInt(startHours) * 60 + parseInt(startMinutes);
                    var stopTime = r.stop_time.split(":");
                    var stopHours = stopTime[0];
                    var stopMinutes = stopTime[1];
                    var stopMinutesTime = parseInt(stopHours) * 60 + parseInt(stopMinutes);

                    var today = new Date();
                    var curMinutesTime = today.getHours() * 60 + today.getMinutes();

                    var targetday_milliseconds=today.getTime() - 1000*60*60*24*1;
                    var yesterday = new Date();
                    yesterday.setTime(targetday_milliseconds);

                    targetday_milliseconds = today.getTime() + 1000*60*60*24*1;
                    var tomorrow = new Date();
                    tomorrow.setTime(targetday_milliseconds);

                    var startFormatDate = "";
                    var stopFormatDate = "";
                    if (startMinutesTime < stopMinutesTime) {
                        if (curMinutesTime < startMinutesTime) {
                            yesterday.setHours(parseInt(startHours));
                            yesterday.setMinutes(parseInt(startMinutes));
                            yesterday.setSeconds(0);
                            startFormatDate = yesterday.format("yyyy-MM-dd hh:mm:ss");
                            yesterday.setHours(parseInt(stopHours));
                            yesterday.setMinutes(parseInt(stopMinutes));
                            stopFormatDate = yesterday.format("yyyy-MM-dd hh:mm:ss");
                        } else {
                            today.setHours(parseInt(startHours));
                            today.setMinutes(parseInt(startMinutes));
                            today.setSeconds(0);
                            startFormatDate = today.format("yyyy-MM-dd hh:mm:ss");
                            today.setHours(parseInt(stopHours));
                            today.setMinutes(parseInt(stopMinutes));
                            stopFormatDate = today.format("yyyy-MM-dd hh:mm:ss");
                        }
                    } else {
                        if (curMinutesTime < startMinutesTime) {
                            yesterday.setHours(parseInt(startHours));
                            yesterday.setMinutes(parseInt(startMinutes));
                            yesterday.setSeconds(0);
                            startFormatDate = yesterday.format("yyyy-MM-dd hh:mm:ss");
                            today.setHours(parseInt(stopHours));
                            today.setMinutes(parseInt(stopMinutes));
                            today.setSeconds(0);
                            stopFormatDate = today.format("yyyy-MM-dd hh:mm:ss");
                        } else {
                            today.setHours(parseInt(startHours));
                            today.setMinutes(parseInt(startMinutes));
                            today.setSeconds(0);
                            startFormatDate = today.format("yyyy-MM-dd hh:mm:ss");
                            tomorrow.setHours(parseInt(stopHours));
                            tomorrow.setMinutes(parseInt(stopMinutes));
                            tomorrow.setSeconds(0);
                            stopFormatDate = tomorrow.format("yyyy-MM-dd hh:mm:ss");
                        }
                    }

                    var href = "/epg/dadian_news.html?" + r.channel_code + "=" + r.channel_ip + "&free_type=0&channel_id=" + r.channel_id + "&cn=" + r.channel_name + "&location=&locationCategory=-1&startTime=" + startFormatDate + "&endTime=" + stopFormatDate;
                    if (r.count == 0) {
                        return News.Config.NEWS_STATUS[v] + " | " + str;
                    } else {
                        return News.Config.NEWS_STATUS[v] + " | " + "<a href='" + href + "' target='_blank'>" + str + "</a>";
                    }
                },
                operate:function(v,r) {
                    var str = "<a href='/epg/news_edit.html?programId=" + r.program_id + "' target='_blank'>修改</a>";
                    str += " | " + "<a href='javascript:void(0);' onclick='News.Util.del(" + r.program_id + ")' target='_blank'>删除</a>";
                    //str += " | " + "<a href=''target='_blank'>当日时间重置</a>";
                    return str;
                },
                statisticsShow:function(v,r) {
                    return "<a href='' target='_blank'>拆条相关数据</a>";
                }

			},
			del: function(program_id){
                var self = this;
                if(window.confirm('是否从自动拆条列表中删除该节目？')) {
                    var params = {func: 'delete_ablum', program_id: program_id};
                    News.Dao.modify(params, function(){
                        $('.query-btn').click();
                    });
                    return true;
                }
            }

		});
});
define(
	'../newsDetails/NewsDetails',['require','exports','module'],function(require, exports, module){
		window.NewsDetails = window.NewsDetails || { version : '1.0' };
		//Video公共配置集合，键值对象
		NewsDetails.Config = NewsDetails.Config || {};
		NewsDetails.Util = NewsDetails.Util || {};

        NewsDetails.Constant = {
            baseApiUrl:(auth.dev() ? "http://10.23.70.33:7000/":"http://dot.live.qiyi.domain/"),
            devMode: auth.dev()
        }

        NewsDetails.urlConfig = (function () {
            var useUrl = NewsDetails.Constant.baseApiUrl;
            var modify = useUrl+"v1/channel/modify";
            var channel = useUrl+"v1/channel";
            var machinelist= useUrl+"v1/channel/machinelist";
            var machinemodify = useUrl + "v1/channel/machinemodify";
            return {
                modifyUrl:modify,
                machinemodifyUrl:machinemodify,
                channelUrl:channel,
                machinelistUrl:machinelist
            }
        })()
	}
);
define(
	'../newsDetails/NewsDetails.Action',['require','exports','module'],function(require, exports, module){

        NewsDetails.Action = (function() {
			var newsDetailsGrid = null;
            var getNewsDetailsGrid = function(options) {
                if (!newsDetailsGrid) {

                    newsDetailsGrid = new NewsDetails.Grid($.extend(true, {
                        '$container': $('#NewsDetailsListContainer'),
                        type: 0
                    }, options));
                }
                return newsDetailsGrid;
            };
            var newsDetailsGridRun = function(options) {
                newsDetailsGrid = getNewsDetailsGrid(options);
                newsDetailsGrid.run();
            };
			var run = function() {
                /* videoQueryRun();*/
                newsDetailsGridRun({});
            };
            return {
                run: run,
				getNewsDetailsGrid:getNewsDetailsGrid
            };
        })();
	}
);
define('../newsDetails/NewsDetails.Config',['require','exports','module'],function(require, exports, module) {

    NewsDetails.Config = {

		REPEAT_INFO : ["周一","周二","周三","周四","周五","周六","周日"], //播放日期
        REGION_LIST: ['cq', 'sh', 'bj'],
        REGION_CH_LIST: ['重庆', '上海', '北京'],

        IP_LINK_AREA: {},

        NEWS_STATUS_NAME: ['未发布', '发布', '删除', '自动删除'],

			TABLE_COLMODEL_CONFIG: {
				'newsName': {
					name: 'newsName',
					title: false,
					index: 'newsName',
					align:'center',
					sortable: false,
					width: 100
				},
				'channelName': {
                    name: 'channelName',
                    title: false,
                    index: 'channelName',
                    align:'center',
                    sortable: false,
                    width: 100
                },
                'serverRegion': {
                    name: 'serverRegion',
                    title: false,
                    index: 'serverRegion',
                    align:'center',
                    sortable: false,
                    width: 80
                },
                'serverIp': {
                    name: 'serverIp',
                    title: false,
                    index: 'serverIp',
                    align:'center',
                    sortable: false,
                    width: 100
                },
				'productTime': {
					name: 'productTime',
					title: false,
					index: 'productTime',
					align:'center',
					width: 100,
					sortable: false
				},
				'status': {
					name: 'status',
					title: false,
					index: 'status',
					align:'center',
					sortable: false,
					width: 80,
					formatter: function(v, o, r) {
                        return NewsDetails.Util.formatter.status(v,r);
                    }
				},
				'intelligentTitle': {
					name: 'intelligentTitle',
					title: false,
					index: 'intelligentTitle',
					width: 230,
					align:'center',
					sortable: false
				},
				'submitTitle': {
                    name: 'submitTitle',
                    title: false,
                    index: 'submitTitle',
                    width: 230,
                    align:'center',
                    sortable: false
                },
                'percentTitle': {
                    name: 'percentTitle',
                    title: false,
                    index: 'percentTitle',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'intelligentStartNum': {
                    name: 'intelligentStartNum',
                    title: false,
                    index: 'intelligentStartNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'submitStartNum': {
                    name: 'submitStartNum',
                    title: false,
                    index: 'submitStartNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'errorStartNum': {
                    name: 'errorStartNum',
                    title: false,
                    index: 'errorStartNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },

                'intelligentEndNum': {
                    name: 'intelligentEndNum',
                    title: false,
                    index: 'intelligentEndNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'submitEndNum': {
                    name: 'submitEndNum',
                    title: false,
                    index: 'submitEndNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'errorEndNum': {
                    name: 'errorEndNum',
                    title: false,
                    index: 'errorEndNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'excLog': {
                    name: 'excLog',
                    title: false,
                    index: 'excLog',
                    width: 100,
                    align:'center',
                    sortable: false
                },
                'submitUser': {
                    name: 'submitUser',
                    title: false,
                    index: 'submitUser',
                    width: 100,
                    align:'center',
                    sortable: false
                }

			},

			TABLE: {
			    url: "/api/newsDetails/list",
			    rowNum:20,
			    multiselect: false,

			    loadBeforeSend:function(xhr, settings){
                    var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                    xhr.setRequestHeader('Sign',auth.sign);
                    xhr.setRequestHeader("Time",auth.clientTime);
                    xhr.setRequestHeader("From",auth.from);
                    return true;
                },

			    datatype: "local",
			    loadtext: '加载中...',
                loadui: "block",
                mtype: "post",
				colNames: ["新闻节目名称", "所属电视台", "服务器", "服务器IP", "日期", "状态", "识别的标题", "发布的标题",
				"标题准确度","识别的入点","发布的入点","入点误差","识别的出点","发布的出点","出点误差","异常提示","审核人"
				],
				colModel: ['newsName', 'channelName', 'serverRegion', 'serverIp', 'productTime', 'status', 'intelligentTitle',
				 'submitTitle', 'percentTitle', 'intelligentStartNum', 'submitStartNum', 'errorStartNum', 'intelligentEndNum',
                 'submitEndNum','errorEndNum','excLog','submitUser'
				]
			}
		};
});
define(
	'../newsDetails/NewsDetails.Dao',['require','exports','module'],function(require, exports, module){

        NewsDetails.Dao = $.extend({}, Ancestor.Dao, {
            getList: function (data, callback) {
                var options = {
                    type: "get",
                    url: NewsDetails.urlConfig.channelUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            redirect: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options,'/redirect');
            }

        });
	}
);
define(
    '../newsDetails/NewsDetails.Grid',['require','exports','module'],function(require, exports, module) {

        NewsDetails.Grid = function(options) {
            this.dao = NewsDetails.Dao;
            this.config = NewsDetails.Config;
            this.util = NewsDetails.Util;
            this.options = options || {};
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);

        };

        Com.inherits(NewsDetails.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
            },

            perpareData: function() {
                var self = this;
                var username = $("div.user a.name").html();
                var requestData = {url: NewsDetails.urlConfig.machinelistUrl, type: "get",
                                                    params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                  };
                self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                    var parentJDom = $("select[name=serverRegion]");
                    var hasDataRegion = [];

                    $("<option>", {value: "all", html: "全部"}).appendTo(parentJDom);

                    if (data != null && data.response != null && data.response.list) {
                        $.each(data.response.list, function (index, obj) {
                            if (obj[1] >= 0 && obj[1] <= 2) {
                                if (hasDataRegion.indexOf(obj[1]) == -1) {
                                    hasDataRegion.push(obj[1]);
                                }

                                NewsDetails.Config.IP_LINK_AREA[obj[0]] = obj[0] + "[" + NewsDetails.Config.REGION_LIST[obj[1]] + "]";
                            }
                        });
                        $.each(hasDataRegion, function (i, element) {
                            $("<option>", {
                                value: element,
                                html: NewsDetails.Config.REGION_CH_LIST[element]
                            }).appendTo(parentJDom);
                        })
                    } else {
                        console.log("wait to do");
                    }
                });
            },

            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

				$("[type=reset]").click(function(){
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=serverRegion]").change();
				});

                $("select[name=serverRegion]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var username = $("div.user a.name").html();
                    var requestData = {url: NewsDetails.urlConfig.machinelistUrl, type: "get",
                                                        params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                      };

                    self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function(data) {
                        var responseData = data;
                        var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                        if (responseData != null && responseData.response != null && responseData.response.list != null) {
                            $.each(responseData.response.list, function (i, obj) {
                                if ((eqVal == null && obj[1] >= 0 && obj[1] <= 2) || eqVal == obj[1]) {
                                    $("<option>", {
                                        value: obj[0],
                                        html: NewsDetails.Config.IP_LINK_AREA[obj[0]]
                                    }).appendTo(selectJDom);
                                }
                            })
                        }
                    });

                });
                $("select[name=serverRegion]").change();
			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });
                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "maxDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();

                self.echoQuery();

                options = $.extend(true, {
                    width: 1850,
                   // multiselect: true,
                    multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
            },

            initGrid: function(options, callback) {
                var self = this;
                var params = self.getParam();

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

                //params.rowNum=10;

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                   postData: $.extend(true, {}, params),

                }, gridConfig, options);

                // $grid.jqGrid('scroll', {});

                //console.log(options	);

                $grid.jqGrid(options);

            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return false;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')
						{
							if(this.checked)
							{
								checkboxVal.push($(this).val());
							}
						}
						else
						{
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },

			del : function(channel_id,ablum_id){
                var self = this;

                if(window.confirm('是否确认删除该专辑信息？')){

                    return true;
                }
            }


        });

    }
);
define('../newsDetails/NewsDetails.Util',['require','exports','module'],function(require, exports, module) {
	NewsDetails.Util = $.extend(true, {}, Ancestor.Util, {
			formatter: {
			    status: function (cellvalue, options, rowObject) {
                    return NewsDetails.Config.NEWS_STATUS_NAME[cellvalue];
                },

                channel_ip: function (cellvalue, options, rowObject) {
                    if (cellvalue == null || NewsDetails.Config.IP_LINK_AREA[cellvalue] == null) {
                        return "未知"
                    }
                    return NewsDetails.Config.IP_LINK_AREA[cellvalue]
                },
                repeatInfo:function(v,r) {
                    var str = "";
                    for(var i in r.repeat_info)
                    {
                        str += NewsDetails.Config.REPEAT_INFO[r.repeat_info[i]-1]+',';
                    }

                    return str.substr(0,str.length-1);
                },
			}


		});
});
define(
	'../newsStatistic/NewsStatistic',['require','exports','module'],function(require, exports, module){
		window.NewsStatistic = window.NewsStatistic || { version : '1.0' };
		//Video公共配置集合，键值对象
		NewsStatistic.Config = NewsStatistic.Config || {};
		NewsStatistic.Util = NewsStatistic.Util || {};

        NewsStatistic.Constant = {
            baseApiUrl:(auth.dev() ? "http://10.23.70.33:7000/":"http://dot.live.qiyi.domain/"),
            devMode: auth.dev()
        }

        NewsStatistic.urlConfig = (function () {
            var useUrl = NewsStatistic.Constant.baseApiUrl;
            var modify = useUrl+"v1/channel/modify";
            var channel = useUrl+"v1/channel";
            var machinelist= useUrl+"v1/channel/machinelist";
            var machinemodify = useUrl + "v1/channel/machinemodify";
            return {
                modifyUrl:modify,
                machinemodifyUrl:machinemodify,
                channelUrl:channel,
                machinelistUrl:machinelist
            }
        })()
	}
);
define(
	'../newsStatistic/NewsStatistic.Action',['require','exports','module'],function(require, exports, module){

        NewsStatistic.Action = (function() {
			var newsStatisticGrid = null;
            var getNewsStatisticGrid = function(options) {
                if (!newsStatisticGrid) {

                    newsStatisticGrid = new NewsStatistic.Grid($.extend(true, {
                        '$container': $('#NewsStatisticListContainer'),
                        type: 0
                    }, options));
                }
                return newsStatisticGrid;
            };
            var newsStatisticGridRun = function(options) {
                newsStatisticGrid = getNewsStatisticGrid(options);
                newsStatisticGrid.run();
            };
			var run = function() {
                /* videoQueryRun();*/
                newsStatisticGridRun({});
            };
            return {
                run: run,
				getNewsStatisticGrid:getNewsStatisticGrid
            };
        })();
	}
);
define('../newsStatistic/NewsStatistic.Config',['require','exports','module'],function(require, exports, module) {

    NewsStatistic.Config = {

		REPEAT_INFO : ["周一","周二","周三","周四","周五","周六","周日"], //播放日期
        REGION_LIST: ['cq', 'sh', 'bj'],
        REGION_CH_LIST: ['重庆', '上海', '北京'],

        IP_LINK_AREA: {},

			TABLE_COLMODEL_CONFIG: {
				'newsName': {
					name: 'newsName',
					title: false,
					index: 'newsName',
					align:'center',
					sortable: false,
					width: 100
				},
				'channelName': {
                    name: 'channelName',
                    title: false,
                    index: 'channelName',
                    align:'center',
                    sortable: false,
                    width: 100
                },
                'serverRegion': {
                    name: 'serverRegion',
                    title: false,
                    index: 'serverRegion',
                    align:'center',
                    sortable: false,
                    width: 80
                },
                'serverIp': {
                    name: 'serverIp',
                    title: false,
                    index: 'serverIp',
                    align:'center',
                    sortable: false,
                    width: 100
                },
				'productTime': {
					name: 'productTime',
					title: false,
					index: 'productTime',
					align:'center',
					width: 100,
					sortable: false
				},
				'costTime': {
					name: 'costTime',
					title: false,
					index: 'costTime',
					width: 230,
					align:'center',
					sortable: false
				},
				'avgPercentTitle': {                    //标题平均准确率
                    name: 'avgPercentTitle',
                    title: false,
                    index: 'avgPercentTitle',
                    width: 230,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percent(v,r);
                    }
                },
                'percentWord': {                        //文字识别准确率
                    name: 'percentWord',
                    title: false,
                    index: 'percentWord',
                    width: 80,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percentWord(v,r);
                    }
                },
                'avgErrorStartNum': {                   //入点平均误差
                    name: 'avgErrorStartNum',
                    title: false,
                    index: 'avgErrorStartNum',
                    width: 80,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percent(v,r);
                    }
                },
                'percentStartNum': {                    //入点精确度
                    name: 'percentStartNum',
                    title: false,
                    index: 'percentStartNum',
                    width: 80,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percentStartNum(v,r);
                    }
                },
                'avgErrorEndNum': {                      //出点平均误差
                    name: 'avgErrorEndNum',
                    title: false,
                    index: 'avgErrorEndNum',
                    width: 80,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percent(v,r);
                    }
                },

                'percentEndNum': {                  //出点精确度
                    name: 'percentEndNum',
                    title: false,
                    index: 'percentEndNum',
                    width: 80,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percentEndNum(v,r);
                    }
                },
                'correctNewsNum': {                 //拆条后正确单条新闻视频的数量
                    name: 'correctNewsNum',
                    title: false,
                    index: 'correctNewsNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'totalNewsNum': {                    //拆条后生成视频的总数量
                    name: 'totalNewsNum',
                    title: false,
                    index: 'totalNewsNum',
                    width: 80,
                    align:'center',
                    sortable: false
                },
                'percentNews': {                         //拆条准确率
                    name: 'percentNews',
                    title: false,
                    index: 'percentNews',
                    width: 100,
                    align:'center',
                    sortable: false,
                    formatter: function(v, o, r) {
                        return NewsStatistic.Util.formatter.percentNews(v,r);
                    }
                }

			},

			TABLE: {
			    url: "/api/newsDetails/st",
			    rowNum:20,
			    multiselect: false,

			    loadBeforeSend:function(xhr, settings){
                    var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                    xhr.setRequestHeader('Sign',auth.sign);
                    xhr.setRequestHeader("Time",auth.clientTime);
                    xhr.setRequestHeader("From",auth.from);
                    return true;
                },

			    datatype: "local",
			    loadtext: '加载中...',
                loadui: "block",
                mtype: "post",
				colNames: ["新闻节目名称", "所属电视台", "服务器", "服务器IP", "日期", "拆条时间", "标题平均准确率", "文字识别准确率",
				"入点平均误差（帧）","入点精确度","出点平均误差（帧）","出点精确度","拆条后正确单条新闻视频数量","拆条后生成视频总数量","拆条准确率"
				],
				colModel: ['newsName', 'channelName', 'serverRegion', 'serverIp', 'productTime', 'costTime', 'avgPercentTitle',
				 'percentWord', 'avgErrorStartNum', 'percentStartNum', 'avgErrorEndNum', 'percentEndNum', 'correctNewsNum',
                 'totalNewsNum','percentNews'
				]
			}
		};
});
define(
	'../newsStatistic/NewsStatistic.Dao',['require','exports','module'],function(require, exports, module){

        NewsStatistic.Dao = $.extend({}, Ancestor.Dao, {
            getList: function (data, callback) {
                var options = {
                    type: "get",
                    url: NewsStatistic.urlConfig.channelUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            redirect: function(data, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options,'/redirect');
            }

        });
	}
);
define(
    '../newsStatistic/NewsStatistic.Grid',['require','exports','module'],function(require, exports, module) {

        NewsStatistic.Grid = function(options) {
            this.dao = NewsStatistic.Dao;
            this.config = NewsStatistic.Config;
            this.util = NewsStatistic.Util;
            this.options = options || {};
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);

        };

        Com.inherits(NewsStatistic.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
            },

            perpareData: function() {
                var self = this;
                var username = $("div.user a.name").html();
                var requestData = {url: NewsStatistic.urlConfig.machinelistUrl, type: "get",
                                                    params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                  };
                self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function (data) {
                    var parentJDom = $("select[name=serverRegion]");
                    var hasDataRegion = [];

                    $("<option>", {value: "all", html: "全部"}).appendTo(parentJDom);

                    if (data != null && data.response != null && data.response.list) {
                        $.each(data.response.list, function (index, obj) {
                            if (obj[1] >= 0 && obj[1] <= 2) {
                                if (hasDataRegion.indexOf(obj[1]) == -1) {
                                    hasDataRegion.push(obj[1]);
                                }

                                NewsStatistic.Config.IP_LINK_AREA[obj[0]] = obj[0] + "[" + NewsStatistic.Config.REGION_LIST[obj[1]] + "]";
                            }
                        });
                        $.each(hasDataRegion, function (i, element) {
                            $("<option>", {
                                value: element,
                                html: NewsStatistic.Config.REGION_CH_LIST[element]
                            }).appendTo(parentJDom);
                        })
                    } else {
                        console.log("wait to do");
                    }
                });
            },

            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

				$("[type=reset]").click(function(){
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=serverRegion]").change();
				});

                $("select[name=serverRegion]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var username = $("div.user a.name").html();
                    var requestData = {url: NewsStatistic.urlConfig.machinelistUrl, type: "get",
                                                        params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                                                      };

                    self.dao.redirect({"request": JSON.stringify(requestData), "timeSign": new Date().getTime()}, function(data) {
                        var responseData = data;
                        var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                        if (responseData != null && responseData.response != null && responseData.response.list != null) {
                            $.each(responseData.response.list, function (i, obj) {
                                if ((eqVal == null && obj[1] >= 0 && obj[1] <= 2) || eqVal == obj[1]) {
                                    $("<option>", {
                                        value: obj[0],
                                        html: NewsStatistic.Config.IP_LINK_AREA[obj[0]]
                                    }).appendTo(selectJDom);
                                }
                            })
                        }
                    });

                });
                $("select[name=serverRegion]").change();
			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });
                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "maxDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();

                self.echoQuery();

                options = $.extend(true, {
                    width: 1850,
                   // multiselect: true,
                    multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
            },

            initGrid: function(options, callback) {
                var self = this;
                var params = self.getParam();

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

                //params.rowNum=10;

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                   postData: $.extend(true, {}, params),

                }, gridConfig, options);

                // $grid.jqGrid('scroll', {});

                //console.log(options	);

                $grid.jqGrid(options);

            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return false;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')
						{
							if(this.checked)
							{
								checkboxVal.push($(this).val());
							}
						}
						else
						{
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },

			del : function(channel_id,ablum_id){
                var self = this;

                if(window.confirm('是否确认删除该专辑信息？')){

                    return true;
                }
            }


        });

    }
);
define('../newsStatistic/NewsStatistic.Util',['require','exports','module'],function(require, exports, module) {
	NewsStatistic.Util = $.extend(true, {}, Ancestor.Util, {
			formatter: {
			    status: function (cellvalue, options, rowObject) {
                    return NewsStatistic.Config.NEWS_STATUS_NAME[cellvalue];
                },

                percent: function(v,r) {
                    return v + "%";
                },

                percentWord:function(v,r) {
                    if (r.errorWordNum == null || r.correctWordNum == null) {
                        return "";
                    }
                    if (r.errorWordNum == 0 && r.correctWordNum == 0) {
                        return "0%";
                    }
                    var percentWord = ((r.correctWordNum / (r.errorWordNum + r.correctWordNum)) * 100) + "%";
                    return percentWord;
                },
                percentStartNum:function(v,r) {
                    if (r.correctStartNum == null || r.totalStartNum == null) {
                        return "";
                    }
                    if (r.correctStartNum == 0 && r.totalStartNum == 0) {
                        return "0%";
                    }
                    var percentStartNum = ((r.correctStartNum / r.totalStartNum) * 100) + "%";
                    return percentStartNum;
                },
                percentEndNum:function(v,r) {
                    if (r.correctEndNum == null || r.totalEndNum == null) {
                        return "";
                    }
                    if (r.correctEndNum == 0 && r.totalEndNum == 0) {
                        return "0%";
                    }
                    var percentEndNum = ((r.correctEndNum / r.totalEndNum) * 100) + "%";
                    return percentEndNum;
                },
                percentNews:function(v,r) {
                    if (r.correctNewsNum == null || r.totalNewsNum == null) {
                        return "";
                    }
                    if (r.correctNewsNum == 0 && r.totalNewsNum == 0) {
                        return "0%";
                    }
                    var percentNews = ((r.correctNewsNum / r.totalNewsNum) * 100) + "%";
                    return percentNews;
                }
			}


		});
});
define(
    '../director/Director',['require','exports','module'],function (require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Director = window.Director || {
            version: '1.0'
        };
        Director.Constant = {
            thirdUrl_quick_create_preview:"http://ip:port/start",
            devMode: auth.dev()
        }
        Director.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var directorListUrl = useUrl + "director/list";
            var directorAddUrl = useUrl + "director/create";
            var directorStopUrl = useUrl + "director/stop";
            var directorStartUrl = useUrl + "director/start";
            var directorEditUrl = useUrl + "director/edit";
            var resourceListUrl = useUrl + "director/resource/getList";
            var resourceAddUrl = useUrl + "director/resource/add";
            var resourceEditUrl = useUrl + "director/resource/edit";
            var resourceDelUrl = useUrl + "director/resource/del";
            var directorLogUrl = useUrl + "director/log/list";
            var switchBackUpUrl = useUrl + "director/backup/switch";
            var switchResourceUrl = useUrl + "director/resource/switch";
            var queryRtmpUrl = useUrl + "program/getRtmpStream";
            var releaseAllUrl = useUrl + "director/releaseAll";
            var releaseUrl = useUrl + "director/release";
            var programSearchUrl = useUrl + "program/search";
            var effectAddUrl = useUrl + "director/effect/add";
            var effectEditUrl = useUrl + "director/effect/edit";
            var effectDelUrl = useUrl + "director/effect/del";
            var effectListUrl = useUrl + "director/effect/list";
            var commentaryListUrl = useUrl + "director/commentary/list";
            var commentaryDelUrl = useUrl + "director/commentary/del";
            var commentaryEditUrl = useUrl + "director/commentary/edit";
			var directorSetMainResourceUrl = useUrl + "director/setMainResource";
            var setResourcePlayCountsUrl = useUrl + "director/resource/setPlayCounts";

            return {
                listUrl: directorListUrl,
                addUrl: directorAddUrl,
                startUrl: directorStartUrl,
                stopUrl: directorStopUrl,
                editUrl: directorEditUrl,
                resourceListUrl: resourceListUrl,
                addResourceUrl: resourceAddUrl,
                editResourceUrl: resourceEditUrl,
                delResourceUrl: resourceDelUrl,
                directorLogUrl:directorLogUrl,
                switchBackUpUrl:switchBackUpUrl,
                switchResourceUrl:switchResourceUrl,
                queryRtmpUrl:queryRtmpUrl,
                programSearchUrl: programSearchUrl,
                releaseAllUrl:releaseAllUrl,
                releaseUrl:releaseUrl,
                effectAddUrl:effectAddUrl,
                effectEditUrl:effectEditUrl,
                effectDelUrl: effectDelUrl,
                effectListUrl: effectListUrl,
                commentaryListUrl: commentaryListUrl,
                commentaryDelUrl: commentaryDelUrl,
                commentaryEditUrl: commentaryEditUrl,
				directorSetMainResourceUrl: directorSetMainResourceUrl,
                setResourcePlayCountsUrl: setResourcePlayCountsUrl,
            }
        })();


    }
);

/**
 * Created by lemuelwang on 2017/2/22.
 */

define(
    '../director/Director.Action',['require','exports','module'],function (require, exports, module) {


        Director.Action = (function () {
            var editForm = null;
            var directorGrid = null;
            var editRun = function () {
                if (!editForm) {
                    editForm = new Director.Edit($.extend(true, {}, {}));
                }
                editForm.init();

                $("#effectTabs").tabs();
            };

            var libraryRun = function () {
                Ancestor.Config.EPG_AUTH.list = '/director/list';
                if (!directorGrid) {
                    directorGrid = new Director.Grid($.extend(true, {
                        '$container': $('#ProgramListContainer'),
                        $grid: $('#list')
                    }, {}));
                }
                directorGrid.runLibrary();
                console.log('library grid run');
            }

            return {
                editRun: editRun,
                libraryRun: libraryRun
            }
        })();
    }
);


/**
 * Created by lemuelwang on 2017/2/22.
 */
define('../director/Director.Config',['require','exports','module'],function (require, exports, module) {
    Director.Config = $.extend({}, Ancestor.Config, {
            TIME_COLOR_CHANGE: false,
            TABLE_COLMODEL_CONFIG: {
                qipuId: {
                    name: "programQipuId",
                    index: 'programQipuId',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.qipuId(v, o, r);
                    }
                },
                pname: {
                    name: "programName",
                    index: 'programName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.programName(v, o, r);
                    }
                },
                programStatus: {
                    index: 'programStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.programStatus(v, o, r);
                    }
                },
                playStatus: {
                    name: "playStatus",
                    index: 'playStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.playStatus(v, o, r);
                    }
                },
                startPlayTime: {
                    name: "startPlayTime",
                    index: 'startPlayTime',
                    title: false,
                    width: 150,
                    sortable: false,
                    align: "center"
                },
                stopPlayTime: {
                    name: "stopPlayTime",
                    index: 'stopPlayTime',
                    title: false,
                    width: 150,
                    sortable: false,
                    align: "center"
                },
                operator_list: {
                    title: false,
                    width: 220,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.operator_list(v, o, r);
                    }
                },
                log_id: {
                    name: 'id',
                    index: 'id',
                    title: false,
                    sortable: false,
                    hidden: true
                },
                log_addTime: {
                    name: 'addTime',
                    index: 'addTime',
                    sortable: false,
                    title: false,
                    width: 150,
                    align: 'center'
                },
                log_user: {
                    name: 'user',
                    index: 'user',
                    sortable: false,
                    title: false,
                    width: 150
                },
                log_type: {
                    name: 'type',
                    index: 'type',
                    sortable: false,
                    title: false,
                    width: 120,
                    formatter: function (v, o, r) {
                        return Director.Util.formatter.log_type(v, o, r);
                    }
                },
                log_descr: {
                    name: "descr",
                    index: 'descr',
                    title: false,
                    width: 450,
                    sortable: false
                }
            },
            TABLE_LIST: {
                url: Director.urlConfig.listUrl,
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                rowNum: 40,
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                multiselect: false,
                datatype: "local",
                loadtext: '加载中...',
                loadui: "block",
                mtype: "post",
                caption: "导播列表列表",
                pager: "#pager",
                colNames: ["奇谱ID", "节目名称", "节目播放状态", "开始时间", "结束时间", "导播状态", "操作" ],
                colModel: ['qipuId', 'pname', 'programStatus' , 'startPlayTime', 'stopPlayTime', "playStatus", "operator_list"]
            },
            TABLE_LOG: {
                url: Director.urlConfig.directorLogUrl,
                loadBeforeSend: function (xhr, settings) {
                    var auth = Ancestor.Util.getAuth("/director/log/list");
                    xhr.setRequestHeader('Sign', auth.sign);
                    xhr.setRequestHeader("Time", auth.clientTime);
                    xhr.setRequestHeader("From", auth.from);
                    return true;
                },
                multiselect: false,
                loadtext: '加载中...',
                loadui: 'block',
                rowNum: 50,
                mtype: "post",
                datatype: "local",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                colNames: ["ID", "操作时间", "人员", "动作", "备注"],
                colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
                pager: "#log_pager"
            },
            PageBeanResource: null,
            PageBeanBackup: null,
            ImgLogo: null,
            ImgLogoMainResource: null,
            AUTH_LOG_DETAIL: false,
            DURING_CHANGE_SETTINGS: false,
            WAITING_MSG: false,
            HINT_MSG: {
                "-2001": "不能删除默认灾备",
                "-2002": "正在使用当前信号源,不能删除"
            },
            REG_VALIDATE:{
                HTTP_RTMP_UDP:/^(http|rtmp|udp):\/\//,
                RTMP_ONLY:/^rtmp:\/\//
            },

            PageBeanEffectImage: null,
            PageBeanEffectSubtitle: null,
            PageBeanEffectAnimation: null,
            PageBeanEffectAudio: null,
            PageBeanEffectCover: null,
            EffectUploadCommonParams: {
                //auth_token: Com.cookie.get('P00001'),
                auth_token: "5aX4BXG5ZM5c8DEwwm1UefCprtQaAwzuwaA0tNAUZFNp6WJDANvSZGq2bd0WZnm1m2m1KA9f",
                qichuan_bizid: "ppc_daobotai",
                file_type: "jpg",
                business_type: "image",
                file_size: "1"
            },
            EFFECT_UPLOAD_URL: auth.dev() ? "http://10.110.22.78/common_upload" : "http://paopaoupload.iqiyi.com/common_upload",
            EFFECT_LIST: [],
            EFFECT_TYPE: {
                image: 1,
                subtitle: 2,
                animation: 3,
                audio: 4,
            },
            EFFECT_CTRL_KEYDOWN: false,
            EFFECT_BACNEND_URL_PREFIX: auth.dev() ? "http://YW-A2980-D.iqiyi.pps:8001/" : "http://10.10.5.155:8002/",
            EFFECT_DEFAULTS: {
                image: {
                    location: '0,0',
                    extraInfo: '{"animation":0,"enterDuration":1,"stayDuration":1,"exitDuration":1,"loop":0,"interval":0,"playTimes":1,"size":"{\\\"w\\\":100,\\\"h\\\":100}"}'
                }
            }
        }
    )
});

/**
 *
 * Created by lemuelwang on 2017/2/22.
 */


define(
    '../director/Director.Dao',['require','exports','module'],function (require, exports, module) {

        Director.Dao = $.extend({}, EpgWeb.Dao, Ancestor.Dao, {

            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },
            releaseAllDirector: function (data, callback) {
                var options = {
                    url: Director.urlConfig.releaseAllUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/releaseAll');
            },
            releaseDirector: function (data, callback) {
                var options = {
                    url: Director.urlConfig.releaseUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/release');
            },

            stopDirector: function (data, callback) {
                var options = {
                    url: Director.urlConfig.stopUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/director/stop');
            },



            startDirector: function (data, callback) {
                var options = {
                    url: Director.urlConfig.startUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/start');
            },
            getDirector:function(data, callback){
                var options = {
                    url: Director.urlConfig.listUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/list');
            },
            editDirector: function (data, callback) {
                var options = {
                    url: Director.urlConfig.editUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/edit');
            },
            getResourceList: function (data, callback) {
                var options = {
                    url: Director.urlConfig.resourceListUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/getList');
            },
            addResource: function (data, callback) {
                var options = {
                    url: Director.urlConfig.addResourceUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/add');
            },
            delResource: function (data, callback) {
                var options = {
                    url: Director.urlConfig.delResourceUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/del');
            },
            editResource: function (data, callback) {
                var options = {
                    url: Director.urlConfig.editResourceUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/edit');
            },

            switchBackUp: function (data, callback) {
                var options = {
                    url: Director.urlConfig.switchBackUpUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/backup/switch');
            },
            switchResource: function (data, callback) {
                var options = {
                    url: Director.urlConfig.switchResourceUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/switch');
            },
            addEffect: function (data, callback) {
                var options = {
                    url: Director.urlConfig.effectAddUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/effect/add');
            },
            editEffect: function (data, callback) {
                var options = {
                    url: Director.urlConfig.effectEditUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/effect/edit');
            },
            deleteEffect: function (data, callback) {
                var options = {
                    url: Director.urlConfig.effectDelUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/effect/del');
            },

            getEffectList: function (data, callback) {
                var options = {
                    url: Director.urlConfig.effectListUrl,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/effect/list');
            },


            redirectApi: function (data, callback) {
                var options = {
                    url: '/api/director/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    beforeSend: function (request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/redirect');
            },

            getProgram: function (data, callback) {
                var options = {
                    url: Director.urlConfig.programSearchUrl,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/search');
            },
            quickCreatePreviewUrl: function (data, callback) {
                console.log("wait to do");
//                var options = {
//                    url: Director.Constant.thirdUrl_quick_create_preview,
//                    dataType: 'json',
//                    data: data,
//                    method: 'get',
//                    success: function (data) {
//                        callback.call(this, data);
//                    },
//                    error: function (data) {
//                        callback.call(this, data);
//                    }
//                };
//                Ancestor.Dao.ajax(options);
                callback();
            },

            getCommentaryList: function (data, callback) {
                var options = {
                    url: Director.urlConfig.commentaryListUrl,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/commentary/list');
            },

            deleteCommentary: function(data, callback) {
                var options = {
                    url: Director.urlConfig.commentaryDelUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/commentary/del');
            },
            editCommentary: function(data, callback) {
                var options = {
                    url: Director.urlConfig.commentaryEditUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/commentary/edit');
            },
            setDirectorMainResource: function (data, callback) {
                var options = {
                    url: Director.urlConfig.directorSetMainResourceUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/setMainResource');
            },
            setResourcePlayCounts: function (data, callback) {
                var options = {
                    url: Director.urlConfig.setResourcePlayCountsUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/resource/setPlayCounts');
            },
        });

        Director.Dao.cfgName = $.extend({}, EpgWeb.Dao.cfgName, {
            LogType: "director_log",
            oldDelay: -1
        });


    }
);


/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../director/Director.Task',['require','exports','module'],function (require, exports, module) {
        Director.Task = $.extend({}, EpgWeb.Task, {
            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            }
        })
    }
);
define(
    '../director/Director.Grid',['require','exports','module'],function (require, exports, module) {
        Director.Grid = function (options) {
            this.dao = Director.Dao;
            this.config = Director.Config;
            this.task = Director.Task;
            this.options = options || {};
        };
        Com.inherits(Director.Grid, Ancestor.Grid).extend({
            /* program director end */
            initLibraryGrid: function (options) {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    var params = self.getParam();
                    var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                    //params.rowNum=10;
                    options = $.extend(true, {
                        mtype: 'post',
                        postData: $.extend(true, {}, params)
                    }, gridConfig, options);
                    self.$grid.jqGrid(options);
                    self.echoQuery();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            runLibrary: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.bindBasicEvent();
                Director.Util.bindDate("startDate", "endDate");
                self.initLibraryGrid({})
            },

            echoQuery: function () {
                var self = this;
                self.query();
            },

            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },

            reload: function () {
                var self = this;
                var $grid = self.$grid;
                $grid.trigger('reloadGrid');
            },

            getParam: function () {
                var self = this;
                var $container = self.options.$container;

                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {
                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';
                    }
                });

                return params;
            },

            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                $form.find('.query-btn').on('click', function () {
                    self.query();
                    return false;
                });
                $form.find('button[type="reset"]').click(function () {
                    self.resetQueryForm();
                });
            }
            /* program director end */

        })
    }
);
define(
    '../director/Director.Edit',['require','exports','module'],function (require, exports, module) {
        Director.Edit = function (options) {
            this.dao = Director.Dao;
            this.config = Director.Config;
            this.task = Director.Task;
            this.options = options || {};
        };
        Com.inherits(Director.Edit, function () {
        }).extend({
            init: function () {
                var self = this;
                var param_id = Com.url.getParameter("programQipuId");
                if (param_id == null || !param_id.endsWith("23")) {
                    console.log("no such data");
                    return
                }
                var taskArr = self.getInitTaskArr();
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    var entity = Director.Util.getEntity();
                    self.config.ImgLogo = $('<img id="imgLogo" src="img/u743.png" >');
                    self.config.ImgLogoMainResource = $('<img id="imgLogo_mainResource" src="img/u743.png" >');
                    if (entity != null) {
                        Director.Model.initCountDownTimer(entity);
                        Director.Util.initDetailZone(entity);
                        self.fillNavBar();
                        self.config.PageBeanResource = Director.Util.createPageBean();
                        self.config.PageBeanBackup = Director.Util.createPageBean();
                        self.initDialog();
                        self.bindEvent();
                        self.initSuggest();
                        self.initPlayerZone();
                        Director.Player.initPlayer();
                        Director.Player.setCurResourceId(entity.resourceId);
                        Director.Util.getResourceList();
                        Director.Util.getBackUpList();
                        self.setProgramPageUrl(param_id);

                        // 特效相关
                        self.config.PageBeanEffectImage = Director.Util.createPageBean();
                        self.config.PageBeanEffectSubtitle = Director.Util.createPageBean();
                        self.config.PageBeanEffectAnimation = Director.Util.createPageBean();
                        self.config.PageBeanEffectAudio = Director.Util.createPageBean();
                        self.config.PageBeanEffectCover = Director.Util.createPageBean();
                        Director.Util.getEffectList(1);
                        Director.Util.getEffectList(2);
                        Director.Util.getEffectList(3);
                        Director.Util.getEffectList(4);
                        Director.Util.getEffectList(5);

                        self.bindEffectEvent();

                        //解说相关
                        //Director.Commentary.getCommentaryList(false);
                    }
                })
                EpgWeb.ajaxQueue.startLoad();
            },

            getInitTaskArr: function () {
                var taskArr = [];
                var param_id = Com.url.getParameter("programQipuId");
                taskArr.push({
                    regName: "entity",
                    options: {
                        type: "post",
                        url: Director.urlConfig.listUrl,
                        dataType: "json",
                        data: {qipuId: param_id, fullMode: "true"}
                    }
                });
                return taskArr;
            },


            fillNavBar: function () {
                // var navDiv = $("#navDiv");
                // navDiv.tabs({active: 0});
            },
            initDialog: function () {
                var self = this;
                $("#dlg_preview").dialog({
                    title: "预览",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "关闭",
                            click: function () {
                                $("#dlg_preview").find("object").remove();
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_settings").dialog({
                    title: "设置",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                Director.Util.submitEditDirector();
                                $(this).dialog("close");
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_add_alternatePlay").dialog({
                    title: "添加灾备",
                    autoOpen: false,
                    width: 720,
                    height: 400,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitAddBackUp()) {
                                    $("label[name=hint-id]").html("");
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $("label[name=hint-id]").html("");
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_add_signal").dialog({
                    title: "添加信号源",
                    autoOpen: false,
                    width: 720,
                    height: 400,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitAddSignal()) {
                                    $("label[name=hint-id]").html("");
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $("label[name=hint-id]").html("");
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_edit_image").dialog({
                    title: "动画编辑",
                    autoOpen: false,
                    width: 560,
                    height: 450,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitEditEffect(1)) {
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $("label[name=hint-id]").html("");
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_edit_subtitle").dialog({
                    title: "字幕编辑",
                    autoOpen: false,
                    width: 620,
                    height: 450,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitEditEffect(2)) {
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_edit_animation").dialog({
                    title: "动画编辑",
                    autoOpen: false,
                    width: 620,
                    height: 450,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitEditEffect(3)) {
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $("label[name=hint-id]").html("");
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $("#dlg_edit_cover").dialog({
                    title: "遮标编辑",
                    autoOpen: false,
                    width: 620,
                    height: 450,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if (Director.Util.submitEditEffect(5)) {
                                    $(this).dialog("close");
                                }
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                $("label[name=hint-id]").html("");
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                var btnCls1Arr = "dlg_preview,dlg_settings,dlg_add_alternatePlay,dlg_add_signal,dlg_edit_image,dlg_edit_subtitle,dlg_edit_animation,dlg_edit_cover".split(",");
                $.each(btnCls1Arr, function (i, element) {
                    $("div[aria-describedby=" + element + "]").find("div.ui-dialog-buttonset").find("button:eq(0)").addClass("btn-primary");
                    $("div[aria-describedby=" + element + "]").find("div.ui-dialog-buttonset").find("button").addClass("btn");
                })
                $("button[name=query_system_preview_url]").on("click", function (event) {
                    Director.Util.quickCreatePreviewUrl( )
                })
            },

            bindEvent: function () {
                var self = this;
                $("button[name=changeBtn]").bind("click", function (event) {
                    var currentTarget = $(event.currentTarget);
                    if (currentTarget.attr("data-key") == "switchBackUp") {
                        Director.Util.switchBackUp();
                    }
//                    else if(currentTarget.attr("data-key") == "recoverDelay"){
//                        Director.Util.recoverDelay();
//                    }
                })


                $("a[name=preview_link]").bind("click", function (event) {
                    if (Director.Config.DURING_CHANGE_SETTINGS) {
                        SystemDialog.queryAlert("正在切换设置，请稍后操作");
                        return;
                    }
                    //$("#dlg_preview").html('<div id="flv_preview" style="width:480px;height: 270px;background-color:black;color:white;"></div>');
                    //Director.Player.createPreview();
                    //$("#dlg_preview").dialog("open");
                    $('#flv_preview_container').html('<div id="flv_preview_foreground" style="width:410px;height:255px;background-color:black;color:white;"></div>');
                    $('#director_detail_player').css('z-index', 1);
                    Director.Player.createFlvPreview();
                })

                $("button[name=closePreview]").bind("click", function (e) {
                    $('#director_detail_player').css('z-index', -1);
                    $('#flv_preview_container').html('');
                });

                $("button[name=btn_settings]").bind("click", function (event) {
                    var entity = Director.Util.getEntity();
                    if (Director.Config.DURING_CHANGE_SETTINGS) {
                        SystemDialog.queryAlert("正在切换设置，请稍后操作");
                        return;
                    }
                    self.initSettings(entity.startPlayTime < EpgWeb.Util.formatDateTimeFormat(new Date()));
                })
                var self = this;
                var signalParent = $("#dlg_add_signal");
                signalParent.find("select[name=signal_type]").bind("change", function (event) {
                    var $curTarget = $(event.currentTarget);
                    var selectedValue = $curTarget.val();
                    self.defaultSignalView(signalParent);
                    signalParent.find("input[name=signal_url_" + selectedValue + "]").show();
                    if (selectedValue === "2") {
                        //$("#signal_preview_div").show();
                    //    $("button[name=query_system_preview_url]").css('display', 'inline-block');
                    }
                    if (selectedValue === "0" || selectedValue === "2") {
                        signalParent.find("#div_set_main_resource").show();
                        var resources = Director.Config.PageBeanResource.getSource().length;
                        var director = Director.Util.getEntity();
                        if (resources > 0 && director.mainResourceId != 0) {
                            signalParent.find("input[name=set_main_resource]").removeAttr("checked");
                        }
                    } else {
                        signalParent.find("#div_set_main_resource").hide();
                    }
                })
            },
            initSettings: function (isStarted) {
                var parent = $("#dlg_settings");
                parent.dialog("open");
                var entity = Director.Util.getEntity();
                parent.find("input[name=input_out_url]").val(entity.outputUrl);
                parent.find("input[name=delay]").val(entity.delay);
                parent.find("select[name=stream_type]").val(entity.outputStreamType);
                if (isStarted) {
                    parent.find("input[name=delay]").prop("disabled", "disabled");
                    parent.find("select[name=stream_type]").prop("disabled", "disabled")
                } else {
                    parent.find("input[name=delay]").removeAttr("disabled");
                    parent.find("select[name=stream_type]").removeAttr("disabled")
                }
            },
            initPlayerZone: function () {
                Director.Util.initDefaultResourceZone();
                Director.Util.initDefaultBackupZone();

                //Director.Util.initEffectZone();
            },
            initSuggest: function () {
                var playbackSuggest = {
                    id: "playbackSuggest",
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        select: function (event, object) {
                            $("label[name=hint-id]").html("奇谱ID:" + object.item.qipuId + ";乐高Id:" + object.item.entityId);
                            return true;
                        },
                        getParam: function (term) {
                            $("label[name=hint-id]").html("");
                            var requestData = {
                                url: EpgWeb.Constant.thirdUrl_video_url,
                                type: "get",
                                params: {word: term, type: "properTitle"},
                                needCookie: true
                            };
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }

                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData[self._displayKey] = item["entityId"];
                                itemData["entityId"] = item["entityId"];
                                itemData["qipuId"] = item["qipuId"];
                                itemData["channelName"] = item["channelName"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            var formatArr = [];
                            formatArr.push('<span class="contract-width100">' + item["entityId"] + '</span>');
                            formatArr.push('<span class="contract-width100">' + item["qipuId"] + '</span>');
                            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
                            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                        },
                        header: '<div class="contract-item" >' +
                            '<span class="contract-width100">节目Id</span>' +
                            '<span class="contract-width100">节目qipuId</span>' +
                            '<span class="contract-width150">节目显示名称</span>' +
                            '<span class="contract-width60">频道</span>' +
                            '</div>'
                    }
                };

                var liveSuggest = {
                    id: "liveSuggest",
                    options: {
                        source: EpgWeb.urlConfig.programList,
                        method: "post",
                        multiple: false,
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/program/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            //   this.value = object.item.id + "";
                            //  return false;
                            $("label[name=hint-id]").html("奇谱ID:" + object.item.id);
                            return true;
                        },
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            $("label[name=hint-id]").html("");
                            return {liveType: 2, fromPath: "library", deleteStatus: 0, pname: term}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data.result;
                            }
                            if (!data) {
                                return [];
                            }

                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["pname"];
                                itemData[self._displayKey] = item["qipuId"];
                                itemData["channelName"] = item["channelName"];
                                itemData["startPlayTime"] = item["startPlayTime"]
                                itemData["endPlayTime"] = item["endPlayTime"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            var formatArr = [];
                            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
                            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
                            formatArr.push('<span class="contract-width100">' + item["startPlayTime"] + '</span>');
                            formatArr.push('<span class="contract-width100">' + item["endPlayTime"] + '</span>');
                            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                        },
                        header: '<div class="contract-item" >' +
                            '<span class="contract-width100">节目Id</span>' +
                            '<span class="contract-width150">节目显示名称</span>' +
                            '<span class="contract-width60">频道</span>' +
                            '<span class="contract-width100">开始时间</span>' +
                            '<span class="contract-width100">结束时间</span>' +
                            '</div>'
                    }
                }
                $("input[name=signal_url_1]").suggest(playbackSuggest.options);
                $("input[name=signal_url_0]").suggest(liveSuggest.options);
            },
            defaultSignalView: function (parent) {
                parent.find("input[name^=signal_url_]").hide();
                $("#signal_preview_div").hide();
                parent.find("label[name=hint-id]").html("");
                parent.find("button[name=query_system_preview_url]").hide();
            },

            queryResource: function () {
                console.log("queryResource ");
                //$("#tabPanel_1").html();
            },
            queryBackUpResource: function () {
                console.log("queryBackUpResource ")
            },

            bindEffectEvent: function () {
                var self = this;
                var $imageArea = $("#effect-tabs-1"),
                    $subtitleArea = $("#effect-tabs-2"),
                    $animationArea = $("#effect-tabs-3"),
                    $audioArea = $("#effect-tabs-4");

                var $imageUploadBtn = $imageArea.find("input.uploadBtn");
                var imageParent = $("#dlg_edit_image");
                $imageUploadBtn.val("");
                $imageUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $imageUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = self.config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是图片
                    if (!Director.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式只支持png, jpg, bmp, gif, 请重新上传", type: "error"})
                        return;
                    }


                    self.startUploadFile(params, self.AddEffectImage);

                });

                var loopCheckbox = imageParent.find('input[name=loop]');
                loopCheckbox.bind('change', function (e) {
                    var target = $(e.target);
                    var loopDiv = imageParent.find('#effect-image-loop-div');
                    if (target.is(":checked")) {
                        loopDiv.show();
                    } else {
                        loopDiv.hide();
                    }
                });

                var imageAnmiationSelect = imageParent.find('select[name=animation]');
                imageAnmiationSelect.bind('change', function (e) {
                    var target = $(e.target);
                    var timesDiv = imageParent.find('#effect-image-times-div');
                    if (target.val() == "0") {
                        timesDiv.hide();
                    } else {
                        timesDiv.show();
                    }
                });

                //imageAnmiationSelect.click();

                var $subtitleAddBtn = $subtitleArea.find("button.btnAdd");
                $subtitleAddBtn.bind("click", function (e) {
                    Director.Util.AddSubtitleShow();
                });

                var subtitleParent = $('#dlg_edit_subtitle');
                var uploadSubtitleButton = subtitleParent.find('input.uploadBtn');
                uploadSubtitleButton.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是图片
                    if (!Director.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式只支持png, jpg, bmp, gif, 请重新上传", type: "error"})
                        return;
                    }

                    var img = new Image();
                    img.onload = function () {
                        if (img.width != 1920 || img.height != 70) {
                            EpgWeb.Plugin.showTips({content: "只支持1920X70的图片，请重新上传", type: "error"})
                        } else {
                            self.startUploadFile(params, Director.Util.AddSubtitleBackground);
                        }
                    }

                    img.src = url;

                });

                //subtitleParent.find('textarea[name=content]').keydown(function(e) {
                //    var textarea = $(e.target);
                //
                //    if (e.keycode == 13) {
                //        e.returnValue = false;
                //        e.preventDefault();
                //    }
                //
                //    if(Com.string.getStrLength(textarea.val()) > 200 * 2) {
                //        textarea.val(textarea.val().substring(0, 200));
                //    }
                //})

                var subtitleEffectChangeList = ['select[name=fontName]', 'select[name=fontSize]', 'input[name=fontColor]'];
                $.each(subtitleEffectChangeList, function (i, e) {
                    subtitleParent.find(e).bind("change", function () {
                        Director.Util.dialogSubtitlePreview();
                    })
                });

                //var fontArrays = ['fontBold', 'fontItalic', 'fontUnderline'];
                var fontArrays = ['fontBold'];
                $.each(fontArrays, function (i, e) {
                    var a = subtitleParent.find('a.' + e);
                    a.bind('click', function (event) {
                        $(this).toggleClass('active');
                        $(this).find('input').val($(this).hasClass('active') ? 1 : 0);
                        Director.Util.dialogSubtitlePreview();
                    })
                });

                var subtitleLoopCheckbox = subtitleParent.find('input[name=loop]');
                subtitleLoopCheckbox.bind('change', function (e) {
                    var target = $(e.target);
                    var loopDiv = subtitleParent.find('#effect-subtitle-loop-div');
                    if (target.is(":checked")) {
                        loopDiv.show();
                    } else {
                        loopDiv.hide();
                    }
                });

                var subtitleHorseCheckbox = subtitleParent.find('input[name=horseLamp]');
                subtitleHorseCheckbox.bind('change', function (e) {
                    var target = $(e.target);
                    var loopDiv = subtitleParent.find('#effect-subtitle-loop-container-div');
                    if (target.is(":checked")) {
                        loopDiv.show();
                    } else {
                        loopDiv.hide();
                    }
                });

                var $animationAddBtn = $animationArea.find("button.btnAdd");
                $animationAddBtn.bind("click", function (e) {
                    Director.Util.AddAnimationShow();
                });
                var animationParent = $('#dlg_edit_animation');
                var uploadAUrlBtn = animationParent.find('input.uploadBtnUrl');
                var uploadAForegroundBtn = animationParent.find('input.uploadBtnForeground');
                uploadAUrlBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "video";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是视频
                    if (!Director.Util.isValidVideo(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传动画格式只支持mov, 请重新上传", type: "error"})
                        return;
                    }

                    self.startUploadFile(params, Director.Util.AddAnimationUrl);
                });

                uploadAForegroundBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是图片
                    if (!Director.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式只支持png, jpg, bmp, gif, 请重新上传", type: "error"})
                        return;
                    }

                    self.startUploadFile(params, Director.Util.AddAnimationForeground);
                });

                var animationLoopCheckbox = animationParent.find('input[name=loop]');
                animationLoopCheckbox.bind('change', function (e) {
                    var target = $(e.target);
                    var loopDiv = animationParent.find('#effect-animation-loop-div');
                    if (target.is(":checked")) {
                        loopDiv.show();
                    } else {
                        loopDiv.hide();
                    }
                });

                var $audioUploadBtn = $audioArea.find("input.uploadBtn");
                $audioUploadBtn.val('');
                $audioUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $audioUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = self.config.EffectUploadCommonParams;

                    params.business_type = "audio";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是音频
                    if (!Director.Util.isValidAudio(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传音频格式只支持mp3, 请重新上传", type: "error"})
                        return;
                    }

                    self.startUploadFile(params, self.AddEffectAudio);

                });

                //$(window).keydown(function(e) {
                //    if(e.ctrlKey) {
                //        Director.Config.EFFECT_CTRL_KEYDOWN = true;
                //        //console.log("CTRL keydown")
                //    }
                //}).keyup(function(){
                //    Director.Config.EFFECT_CTRL_KEYDOWN = false;
                //    //console.log("CTRL keyup")
                //});

            },

            AddEffectAudio: function (data, params) {
                var self = this;
                var element = {};

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 4;
                element.name = params.file.name;
                element.location = '';
                element.extraInfo = '{"volumn":20}';

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(4);
                    }
                })
            },

            AddEffectImage: function (data, params) {
                var self = this;
                var element = Director.Config.EFFECT_DEFAULTS['image'];

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 1;
                element.name = params.file.name;

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(1);
                    }
                })
            },

            appendEffect: function (data, type) {
                var htmlArr = [];
                var container = null;
                htmlArr.push(Director.Util.makeUpEffectDiv(data, type));


                switch (type) {
                    case 1:
                        container = $("#effect-images");
                        break;
                }

                container.prepend(htmlArr.join(''));
            },

            startUploadFile: function (params, callback) {
                var self = this;
                var url = self.config.EFFECT_UPLOAD_URL;
                url = url + "?t=1";

                $.each(params, function (k, v) {
                    url = url + "&" + k + "=" + v;
                });

                $.ajax({
                    url: url,
                    method: "post",
                    cache: false,
                    contentType: false,
                    processData: false,
                    xhr: function () {
                        var xhr = jQuery.ajaxSettings.xhr();
                        return xhr;
                    },
                    data: params.file,
                    success: function (data) {
                        if (data.code == "A00000") {
                            console.log("success upload");
                            callback.call(this, data.data, params);
                        }
                    },
                    error: function (data) {

                    }
                })
            },

            setProgramPageUrl: function (qipuId) {
                Director.Dao.getProgram({'programQipuId': qipuId}, function (json) {
                    if (json != null && json.code == 'A00000') {
                        var programData = json.data[0];
                        $('span[name=span_program_name]').html('<a target="_blank" href="' + programData.pageUrl + '">' + programData.name + '</a>');
                    } else {
                        console.log('failed to set pageurl')
                    }
                })
            }
        })
    }
);
define(
    '../director/Director.Player',['require','exports','module'],function (require, exports, module) {
        Director.Player = (function () {
            var params = {};
            params.scale = "noscale";
            params.salign = "tl";
            params.wmode = "transparent";
            params.swliveconnect = "true";
            params.allowfullscreen = "true";
            params.allowscriptaccess = "always";
            params.allownetworking = "all";
            params.bgcolor = "#000000";
            var player = {};
            player.swf = "http://www.iqiyi.com/player/20130702143439/expressInstall.swf";
            player.version = "10.0.0";
            player.liveUrl = "/epg/swfs/broadcastingLivePlayer.swf";
            player.microUrl = "/epg/swfs/SignalPlayer.swf";
            player.effectUrl = "/epg/swfs/SignalPreview.swf";

            var manager = {
                oldId: 0,
                newId: 0
            };

            var recordResource = { };
            var recordBackup = { };

            var delayNotifyMap = {};

            var recordEffectImage = {},
                recordEffectSubtitle = {},
                recordEffectAnimation = {},
                recordEffectAudio = {};

            var effectFlashId = 'effectFlv';

            // 左侧播放器
            function initLeftPlayer(streamUrl) {
                var attributes = {};
                attributes.id = "flashOutPutPreview"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = "flv"

                if(checkFlash()) {
                    swfobject.embedSWF(player.liveUrl, "flv", "100%", "395", player.version, player.swf, flashvars, params, attributes, flashCallBack);
                }else{
                    noFlashTip("flv");
                }
            }

            function initEffectPlayer(streamUrl) {
                var attributes = {};
                attributes.id = "effectFlv"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = effectFlashId,
                flashvars.videoWidth = '640';
                flashvars.videoHeight = '360';
                flashvars.rtmpUrl = streamUrl;
                var effectParams = $.extend(true,{},params) ;
                effectParams.wmode = "opaque";
                swfobject.embedSWF(player.effectUrl, "effectFlv", "100%", "395", player.version, player.swf, flashvars, effectParams, attributes, flashCallBack);
            }

            function initPreviewPlayer(streamUrl) {
                var _attributes = {};
                _attributes.id = "flashOutput"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = "flv_preview"
                //  flashvars =  {url:"rtmp://101.227.188.120:1935/liveshow/rtsh61_ogkrxbsn",type:"rtmp"}
                swfobject.embedSWF(player.liveUrl, "flv_preview", "100%", "270", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
            }


            function initFlvPreviewPlayer(streamUrl) {
                var _attributes = {};
                _attributes.id = "flv_preview_foreground"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl)
                flashvars.flashId = "flv_preview_foreground"
                //  flashvars =  {url:"rtmp://101.227.188.120:1935/liveshow/rtsh61_ogkrxbsn",type:"rtmp"}
                swfobject.embedSWF(player.liveUrl, "flv_preview_foreground", "410", "255", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
            }

            function makeUpFlashvarsByStreamUrl(streamUrl){
                var flashvars = {url: streamUrl};
                if (streamUrl.startsWith("http")) {
                    flashvars.type = "http";
                } else if (streamUrl.startsWith("rtmp")) {
                    flashvars.type = "rtmp";
                }
                return flashvars;
            }

            function flashCallBack(data) {
                console.log(" flashCallBack :" + JSON.stringify(data))
            }


            // flash 交互
            // 方法名：changeSource
            //  参数：id(Int)    当前正在播放的信号源对应的flash player编号
            //   // 缩略直播视频预览播放器
            function initMicroPlayer(element) {
                //wait todo
                var _attributes = {};
                var flashvars = {};
                _attributes.id = "flashPlayer" + element.id
                flashvars = {resourceId: element.id,isBackup:element.isBackup}; // isBackup  0：是普通资源 ，1：灾备资源
                var needQueryRtmp = false;
                switch (element.signalType) {
                    case 0:
                        if (element.signalUrl == null || element.signalUrl.length == 0) {
                            needQueryRtmp = true;
                        }
                        flashvars.picUrl = element.snapshotUrl;
                        break;
                    case 1:
                        flashvars.objectId = Number(element.signalLegoId);
                        flashvars.percentApiUrl = element.productStatusUrl;
                        flashvars.cyclicNum = element.playCounts;
                        break;
                    case 2:
                        flashvars.rtmpUrl = element.signalPreviewUrl;
                        flashvars.picUrl = element.snapshotUrl;
                        break;
                }
                swfobject.embedSWF(player.microUrl, "flash" + element.id, "100%", "100%", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
                if (needQueryRtmp) {
                    getRtmpStreamByResource(element)
                }
            }

            function getRtmpStreamByResource(element) {
                var qipuId = Number(element.signalId)
                var options = {
                    url: Director.urlConfig.queryRtmpUrl,
                    dataType: 'json',
                    data: {qipuId: qipuId},
                    type: "get",
                    success: function (data) {
                        if (data != null && data.code == "A00000") {
                            if (data.data.input_url.length > 0) {
                                sendToFlash("flashPlayer" + element.id, {type: "changeRtmp", data:{rtmpUrl: data.data.input_url}});
                            }
                            console.log("getRtmpStreamByResource suc:" + JSON.stringify(data))
                        }
                    },
                    error: function (data) {
                        console.error("getRtmpStreamByResource fail")
                    }
                }
                $.ajax(options)
            }

            function queryRtmpByResourceId(resourceId) {
                var element = recordResource["flash" + resourceId];
                if (element != null && element.signalType) {
                    getRtmpStreamByResource(element);
                }
            }
            function checkResourceSwitch(resourceId ,time, playCounts){
                var element = recordResource["flash" + resourceId];
                if(element == null ){
                    console.warn("element is null :"+resourceId)
                    return ;
                }
                if(element.isBackup == 1){
                    console.log("灾备资源不处理:"+JSON.stringify(element));
                    return ;
                }
                Director.Util.doResourceSwitch(resourceId,time, playCounts);
            }

//
            function sendToFlash(flashId, obj , needDelay) {
                if(!needDelay){
                    var target = thisMovie(flashId);
                    if (target != null) {
                        console.log("[sendToFlash]"+flashId + ":" + JSON.stringify(obj));
                        try {
                            target.notifyFlash(JSON.stringify(obj));
                        } catch (e) {
                            console.log(e);
                            needDelay = true;
                        }
                    }
                }
                if( needDelay ){
                    if (!delayNotifyMap.hasOwnProperty(flashId)) {
                        delayNotifyMap[flashId] = [];
                    }
                    delayNotifyMap[flashId].push(obj);
                }
            }

            function initPlayer() {
                var self = this;
                var entity = Director.Util.getEntity();

                //entity.outputPreviewUrl = 'rtmp://10.121.86.127/live/test_360p,rtmp://10.121.86.127/live/test_360p_1';

                initLeftPlayer(getOutputPreviewUrl(entity.outputPreviewUrl));
                // initPreviewPlayer(entity.outputUrl);

                var effectPreviewUrl = getEffectPreviewUrl(entity.outputPreviewUrl);
                if(effectPreviewUrl != "") {
                    initEffectPlayer(effectPreviewUrl);
                }else{
                    console.log("not preview url for effect player");
                }
            }

            function getOutputPreviewUrl(url) {
                var urls = new Array();
                urls = url.split(",");
                return urls[0];
            }

            function getEffectPreviewUrl(url) {
                var urls = new Array();
                urls = url.split(",");
                if(urls.length > 1) {
                    return urls[1]
                }else{
                    return "";
                }
            }

            function createPreview(){
                var entity = Director.Util.getEntity();
                initPreviewPlayer(entity.outputUrl);
            }

            function createFlvPreview() {
                var entity = Director.Util.getEntity();
                initFlvPreviewPlayer(entity.outputUrl);
            }

            function notifyHandler(event) {
                switch (event.type) {
                    case "startPlay":
                        console.log("startPlay:" + JSON.stringify(event));
                        checkResourceSwitch( event.data.resourceId,event.data.time == null ? 0 : event.data.time, event.data.cyclicNum);

                        break;
                    case "queryRtmp":
                        queryRtmpByResourceId(event.data.resourceId);
                        break;
                    case "initComplete":
                        console.log("initComplete : " + JSON.stringify(event))
                        doDelayEvent("flashPlayer" + event.data.resourceId);
                        break;
                    case "initPreviewComplete":
                        console.log("initPreviewComplete : " + JSON.stringify(event))
                        if (event.data.flashId == "flv_preview") {
                            doDelayEvent(event.data.flashId);
                        }
                        break;
                    case "initEffectPreviewComplete":
                        console.log("initEffectPreviewComplete: " + JSON.stringify(event));
                        break;
                    case "effectPreviewData":
                        console.log("effectPreviewEditData: " + JSON.stringify(event));
                        Director.Util.submitPreviewAllEffects(event['data']);
                        //Director.Util.batchEditEffect(event['data']);
                        //Director.Util.batchEditEffect(event['data'], function(data) {
                        //    Director.Util.batchStopPreview(data, function(data) {
                        //        Director.Util.batchStartPreview(data, function(data) {
                        //        });
                        //    })
                        //});

                        break;
                    //case "effectPlayData":
                    //    console.log("effectPlayEditData");
                    //    break;
                    case "effectDelete":
                        console.log("effectDelete: " + JSON.stringify(event));
                        Director.Util.notifyStopPreviewEffectByFlash(event['data']);
                        break;
                    case "commentaryPlay":
                        console.log("commentaryPlay: " + JSON.stringify(event));
                        Director.Commentary.playCommentary(event['data']);
                        break;
                    case "commentaryStopPlay":
                        console.log("commentaryStopPlay: " + JSON.stringify(event));
                        Director.Commentary.stopCommentary(event['data']);
                        break;
                    case "commentaryChangeVolumn":
                        console.log("commentaryChangeVolumn : " + JSON.stringify(event));
                        Director.Commentary.changeCommentaryVolumn(event['data']);
                        break;
                    case "commentaryDelete":
                        console.log("commentaryDelete: " + JSON.stringify(event));
                        Director.Commentary.delCommentary(event['data']);
					case "setCyclicNum":
                        console.log("setCyclicNum: " + JSON.stringify(event));
                        Director.Util.notifySetResourcePlayCounts(event['data']);
                        break;
                    case "endPlay":
                        console.log("endPlay: " + JSON.stringify(event));
                        changeFlash();
                        break;
                    case "changeCyclic":
                        console.log("changeCyclic: " + JSON.stringify(event));

                    default :
                        break;
                }
            }

            function doDelayEvent(flashId) {
                if (delayNotifyMap.hasOwnProperty(flashId)) {
                    var waitTodoArr = delayNotifyMap[flashId];
                    if(waitTodoArr.length > 0){
                        delayNotifyMap[flashId] = [];
                        console.log("doDelayEvent start ;"+flashId);
                        $.each(waitTodoArr, function (i, eventObj) {
                            sendToFlash(flashId, eventObj);
                        })
                        console.log("doDelayEvent end ;"+flashId + ";"+JSON.stringify(  delayNotifyMap[flashId]  ));
                    }
                }
            }

            function recordDiff(obj1, obj2) {
                obj1.diff = {hasChange: false};
                if (obj1.signalName != obj2.signalName) {
                    obj1.signalName = obj2.signalName;
                    obj1.diff.hasChange = true;
                    obj1.diff.signalName = obj2.signalName;
                }
                if (obj1.isDefaultBackup != obj2.isDefaultBackup) {
                    obj1.isDefaultBackup = obj2.isDefaultBackup;
                    obj1.diff.hasChange = true;
                    obj1.diff.isDefaultBackup = obj2.isDefaultBackup;
                }
                if (obj1.isMainResource != obj2.isMainResource) {
                    obj1.isMainResource = obj2.isMainResource;
                    obj1.diff.hasChange = true;
                    obj1.diff.isMainResource = obj2.isMainResource;
                }

            }

            function registerResource(dataArr) {
                updateRecord(dataArr, recordResource)
            }

            function registerBackup(dataArr) {
                updateRecord(dataArr, recordBackup)
            }

            function updateRecord(dataArr, recordObj) {
                var tempmap = {};
                $.each(dataArr, function (i, element) {
                    tempmap["flash" + element.id] = element;
                })
                var removeKeyArr = [];
                for (var key in recordObj) {
                    if (tempmap.hasOwnProperty(key)) {
                        recordDiff(recordObj[key], tempmap[key]);
                        delete tempmap[key];
                    } else {
                        removeKeyArr.push(key);
                    }
                }
                $.each(removeKeyArr, function (i, removeKey) {
                    delete recordObj[removeKey];
                })

                doRemovePlayerView(removeKeyArr);
                for (var key in tempmap) {
                    recordObj[key] = tempmap[key];
                    recordObj[key].diff = {isNew: true, hasChange: true};
                }
                doDiffUpdatePlayerView(recordObj);
            }

            function doRemovePlayerView(removeKeyArr) {
                $.each(removeKeyArr, function (i, removeKey) {
                    removeKey = removeKey.replace(/flash/, "");
                    $("div[data-div-id=" + removeKey + "]").remove();
                    console.log("remove child " + removeKey);
                })

            }

            function doDiffUpdatePlayerView(recordObj) {
                for (var key in recordObj) {
                    if (recordObj[key].diff.hasChange == true) {
                        if (recordObj[key].diff.isNew == true) {
                            addPlayerView(recordObj[key])
                        } else {
                            updatePlayerView(recordObj[key])
                        }
                    }
                }
            }

            function addPlayerView(element) {
                var htmlArr = [];
                console.log("element" + JSON.stringify(element))
                if (element.isBackup == 1) {
                    htmlArr.push(Director.Util.makeUpBackUpDiv(element));
                    $("#backUpAddDiv").before(htmlArr.join(""));
                    initMicroPlayer(element)
                } else {
                    if (element.signalType == 0 || element.signalType == 2) {
                        htmlArr.push(Director.Util.makeUpResourceDiv(element));
                    } else {
                        htmlArr.push(Director.Util.makeUpResourceType1Div(element));
                    }
                    $("#resourceAddDiv").before(htmlArr.join(""));
                    initMicroPlayer(element)
                }

                if (element.isDefaultBackup == 1) {
                    $("div[data-div-id=" + element.id + "]").append(Director.Config.ImgLogo);
                }
                if (element.id == manager.newId) {
                    sendToFlash("flashPlayer" + element.id, {type: "changeRes",data: {resourceId:element.id}  } , true)
                }
                if (element.isMainResource) {
                    $("div[data-div-id=" + element.id + "]").append(Director.Config.ImgLogoMainResource);
                }
            }

            function updatePlayerView(element) {
                var elementDom = $("div[data-div-id=" + element.id + "]");
                if (element.diff.hasOwnProperty("signalName")) {
                    elementDom.find("input").val(element.diff.signalName)
                }
                if (element.diff.hasOwnProperty("isDefaultBackup")) {
                    if (element.diff.isDefaultBackup == 1) {
                        $("#imgLogo").appendTo(elementDom);
                    }
                }
                if (element.diff.hasOwnProperty("isMainResource")) {
                    if (element.diff.isMainResource) {
                        $("#imgLogo_mainResource").appendTo(elementDom);
                    }
                }
            }

            function setCurResourceId(resourceId) {
                if (resourceId == manager.newId) {
                    return;
                }
                manager.oldId = manager.newId;
                manager.newId = resourceId;
                console.log("  manager.oldId:"+  manager.oldId +"; manager.newId:"+manager.newId )
            }

                function notifyPlayingChange() {
                var elementDom = null;
                if (manager.oldId > 0) {
                    elementDom = $("div[data-div-id=" + manager.oldId + "]");
                    if (elementDom.length > 0) {
                        console.log("notifyPlayingChange close:" + manager.oldId);
                        sendToFlash("flashPlayer" + manager.oldId, {type: "changeRes", data: {resourceId:manager.newId}})
                    }
                }
                if (manager.newId > 0) {
                    elementDom = $("div[data-div-id=" + manager.newId + "]");
                    if (elementDom.length > 0) {
                        console.log("notifyPlayingChange start: " + manager.newId)
                        sendToFlash("flashPlayer" + manager.newId, {type: "changeRes",data: {resourceId:manager.newId}  })
                    }
                }
            }

            //搭建js与flash互通的环境
            function thisMovie(movieName) {
                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window[movieName];
                } else {
                    return document[movieName];
                }
            }

            function stopVol(flashId){
                sendToFlash(flashId,{type:"changeVoice",data:{value:0}})
            }
            function recoverVol(flashId){
                sendToFlash(flashId,{type:"changeVoice",data:{value:1}})
            }
//            function updatePreviewPlayer( streamUrl){
//                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
//                sendToFlash("flv_preview",{type:"",data:flashvars},true)
//            }

            function addEffect(data) {
                openEditEffect();
                sendToFlash(effectFlashId, {type:"addEffect", data: data});
            }

            function openEditEffect() {
                sendToFlash(effectFlashId, {type: "openEdit"});
            }

            function closeEditEffect(mode) {  // mode: 1 或者 0  (1: 返回预览数据, 0: 不需要数据)
                sendToFlash(effectFlashId, {type: "closeEdit", data:mode});
            }

            function editEffect(data) {
                sendToFlash(effectFlashId, {type:"changeEffect", data: data});
            }

            function removeEffect(eid) {
                sendToFlash(effectFlashId, {type: "removeEffect", data: eid});
            }

            function checkFlash() {
                var flag = false;
                if(window.ActiveXObject){
                    try{
                        var swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                        if(swf){
                            flag = true;
                        }
                    }catch(e){
                    }
                }else{
                    try{
                        var swf = navigator.plugins['Shockwave Flash'];
                        if(swf){
                            flag = true;
                        }
                    }catch(e){
                    }
                }

                if(flag){
                    console.log("flash running ok");
                }else{
                    console.log("flash running error");
                }

                return flag;
            }

            function noFlashTip(elementId) {
                var e = $("#" + elementId);
                if(!e) {
                    return;
                }

                e.html('<div class="need-flash"><p>您没有安装Flash播放器或者Flash播放器版本过低</p><p>请点击<a href="http://get.adobe.com/cn/flashplayer/">这里</a>安装</p><p class="grey">安装完毕之后请刷新页面或者重新启动浏览器</p></div>')
            }

            function changeFlash () {
                var mainResouceId = null;
                var entity = Director.Util.getEntity();
                var mainResourceId = entity.mainResourceId;
                entity.resourceId = mainResourceId;
                if (mainResourceId != null) {
                    setCurResourceId(mainResourceId);
                    notifyPlayingChange();
                }
            }

            return {
                initPlayer: initPlayer,
                notifyJS: notifyHandler,
                registerResource: registerResource,
                registerBackup: registerBackup,
                setCurResourceId: setCurResourceId,
                notifyPlayingChange: notifyPlayingChange,
                stopVol:stopVol,
                recoverVol:recoverVol,
                createPreview:createPreview,
                createFlvPreview:createFlvPreview,
                sendToFlash:sendToFlash,
                addEffect: addEffect,
                openEditEffect: openEditEffect,
                closeEditEffect: closeEditEffect,
                removeEffect: removeEffect,
                notifyHandler: notifyHandler,
                editEffect: editEffect,
                checkFlash: checkFlash
            }
        })()
    }
);
define(
    '../director/Director.Model',['require','exports','module'],function (require, exports, module) {
        Director.Model = (function () {
            var streamTypeConfig = {
                HIGH_DEFINITION: "高清",
                RESOLUTION_720P: "超清720P",
                RESOLUTION_1080P: "1080P"
            }
            var timerModel = {
                countTime: $("span[name=countTimerHint]"),
                dayLabel: $("span[name=span_time_day_label]"),
                day: $("span[name=span_time_day]"),
                hour: $("span[name=span_time_hour]"),
                minute: $("span[name=span_time_minute]"),
                second: $("span[name=span_time_second]"),
                playStatusLabel: $("span[name=span_paly_status_label]"),
                cdId: -1

            };

            var detailModel = {
                name: $("span[name=span_program_name]"),
                qipuId: $("span[name=span_program_id]"),
                delay: $("span[name=span_delay]"),
                outputUrl: $("span[name=span_output_url]"),
                outputStreamType: $("span[name=span_output_stream_type]"),
                startTime: $("span[name=span_startTime]"),
                endTime: $("span[name=span_endTime]")
            }

            function updateTimeModel(darArr) {
                timerModel.dayLabel.hide();
                timerModel.day.hide();
                switch (darArr.length) {
                    case 4:
                        timerModel.day.html(darArr[3] < 10 ? "0" + darArr[3] : darArr[3]);
                        timerModel.dayLabel.show();
                        timerModel.day.show();
                    case 3:
                        timerModel.hour.html(darArr[2] < 10 ? "0" + darArr[2] : darArr[2]);
                    case 2:
                        timerModel.minute.html(darArr[1] < 10 ? "0" + darArr[1] : darArr[1]);
                    case 1:
                        timerModel.second.html(darArr[0] < 10 ? "0" + darArr[0] : darArr[0]);
                        break;
                }
                timerModel.second.addClass("time-brown");
                timerModel.day.addClass("time-brown");
                timerModel.hour.addClass("time-brown");
                timerModel.minute.addClass("time-brown");
            }

            function updateRunningMode() {
                timerModel.countTime.html("正在直播");
                timerModel.countTime.css({color:"#136eb4"});
                timerModel.playStatusLabel.html("").removeClass("play_status_default").addClass("play_status_running");
                timerModel.day.removeClass("time-brown").addClass("time-green");
                timerModel.hour.removeClass("time-brown").addClass("time-green");
                timerModel.minute.removeClass("time-brown").addClass("time-green");
                timerModel.second.removeClass("time-brown").addClass("time-green");
            }
            function updateEndMode(){
               // timerModel.countTime.html("直播结束");
                timerModel.playStatusLabel.html("直播结束").removeClass("play_status_default").removeClass("play_status_running").addClass("play_status_end");
                $("#running_zone").hide();
                $("#end_zone").show();
            }

            function initDetail(entity) {
                detailModel.name.html(entity.programName);
                detailModel.qipuId.html(entity.programQipuId);
                detailModel.delay.html(entity.delay);
                if(entity.outputUrl == null || entity.outputUrl.length < 10){
                    detailModel.outputUrl.html("<p style='color:red'>输出地址为空，请去设置</p>")
                }else{
                    detailModel.outputUrl.html( Director.Util.resizeTextWidth( entity.outputUrl,240));
                }
                detailModel.outputStreamType.html(streamTypeConfig[entity.outputStreamType]);
                var timeArr = entity.startPlayTime.split(/ |:/)
                detailModel.startTime.html('<span style="font-size: 18px">' + timeArr[1] + ":" + timeArr[2] + '</span> (' + timeArr[0] + ')');
                timeArr = entity.stopPlayTime.split(/ |:/)
                detailModel.endTime.html('<span style="font-size: 18px">' + timeArr[1] + ":" + timeArr[2] + '</span> (' + timeArr[0] + ')');
            }

            function initCountDownTimer(entity) {
                timerModel.cdId = setInterval(function () {
                    Director.Util.setTimer(entity.startPlayTime,entity.stopPlayTime)
                }, 500);
            }

            function stopTimer(){
                if(timerModel.cdId > 0){
                    clearInterval(timerModel.cdId);
                    timerModel.cdId = -1;
                }
            }

            function getTimerModel(){
                return timerModel;
            }

            return {
                updateTimeModel: updateTimeModel,
                updateRunningMode: updateRunningMode,
                updateEndMode: updateEndMode,
                initDetail: initDetail,
                initCountDownTimer: initCountDownTimer,
                stopTimer : stopTimer,
                getTimerModel:getTimerModel
            }
        })()
    }
);
/**
 * Created by lemuelwang on 2017/2/22.
 */
define('../director/Director.Util',['require','exports','module'],function (require, exports, module) {

    Director.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                qipuId: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(cellvalue);
                    return "<a target='_blank' href='" + plusUrl + "'>" + cellvalue + "</a>";
                },
                programName: function (cellvalue, options, rowObject) {
                    if (rowObject.playStatus == 3) {

                        return "<a class='disabled'>"+cellvalue+"</a>";
                     } else {
                        return "<a href='javascript:;' onclick='Director.Util.jumpToDirector(" + rowObject.programQipuId + ")'>" + cellvalue + "</a>";
                    }
                },
                programStatus: function (cellvalue, options, rowObject) {
                    var current = EpgWeb.Util.formatDateTimeFormat(new Date());
                    var startTime = new Date(rowObject.startPlayTime);
                    startTime.setDate(startTime.getDate() + 2);//回看时间固定为两天
                    var endTimeStr = EpgWeb.Util.formatDateTimeFormat(startTime);
                    if (current < rowObject.startPlayTime) {
                        return "未开始";
                    } else if (current <= rowObject.stopPlayTime) {
                        return "直播中";
                    } else if (current < endTimeStr) {
                        return "回看中";
                    } else {
                        return "已结束";
                    }
                    return cellvalue;
                },
                playStatus: function (cellvalue, options, rowObject) {
                    var ret = ""
                    switch (rowObject.playStatus) {
                        case 0:
                            ret = "导播未开始";
                            break;
                        case 1:
                            ret = "正在导播";
                            break;
                        case 2:
                            ret = "导播停止";
                            break;
                        case 3:
                            ret = "导播结束";
                            break;
                        default :
                            break;
                    }
                    return ret
                },
                operator_list: function (cellvalue, options, rowObject) {
                    var htmlArr = [];
                    if (rowObject.playStatus == 1) {
                        htmlArr.push("<a href='javascript:;' onclick='Director.Util.stopDirector(" + rowObject.id + ")'>停止导播</a>");
                    } else {
                        htmlArr.push("<a class='disabled'>停止导播</a>");
                    }
                    if (rowObject.playStatus == 1) {
                        htmlArr.push("<a href='javascript:;' onclick='Director.Util.releaseDirector(" + rowObject.id + ")'>资源回收</a>");
                    } else {
                        htmlArr.push("<a class='disabled'>资源回收</a>");
                    }

                    htmlArr.push("<a href='javascript:;' onclick='Director.Util.openHistory(" + rowObject.id + ")'>操作日志</a>");
                    htmlArr.push("<a href='javascript:;' onclick='Director.Util.delDirector(" + rowObject.id + ")'>删除</a>");
                    return htmlArr.join(" ")
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Director.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                }
            },
            stopDirector: function (directorId) {
                Director.Dao.stopDirector({directorId: directorId}, function (data) {
                    Director.Util.reloadListHandler(data)
                });
            },
           releaseDirector: function (directorId) {
               SystemDialog.queryConfirm("回收后不能再次开启导播，确认回收？", function (flag) {
                   if (flag === true) {
                       Director.Dao.releaseDirector({directorId: directorId}, function (data) {
                           if (data != null && data.code == "A00000") {
                               EpgWeb.Plugin.showTips({content: "回收 成功"});
                               $("#list").trigger('reloadGrid');
                           } else {
                               EpgWeb.Plugin.showTips({content: "回收 失败", type: "error"});
                           }
                       })
                   }
               })
            },

            startDirector: function (directorId) {
                Director.Dao.startDirector({ directorId: directorId}, function (data) {
                    Director.Util.reloadListHandler(data)
                });
            },
            jumpToDirector: function (programQipuId) {
                var openUrl = "program_director.html?programQipuId=" + programQipuId
                window.open(openUrl);
            },
            openHistory: function (entityId) {
                Director.Dao.doAuthData({
                    url: '/epg/channel_log.html',
                    doSuccess: function () {
                        Director.Config.AUTH_LOG_DETAIL = true;
                    },
                    doFinal: function () {
                        var tableConfig = $.extend(true, {}, Director.Config.TABLE_LOG);
                        tableConfig.width = Director.Config.AUTH_LOG_DETAIL ? 875 : 425
                        var colModel = tableConfig.colModel;
                        var newColModel = [];
                        var colModelConfig = Director.Config.TABLE_COLMODEL_CONFIG;

                        $.each(colModel, function (i, model) {
                            newColModel.push(colModelConfig[model]);
                        });
                        tableConfig.colModel = newColModel;
                        tableConfig.colModel[4].hidden = !Director.Config.AUTH_LOG_DETAIL;
                        $('#logList').jqGrid(tableConfig);
                        $("#directorLogDiv").dialog({
                            title: "历史记录",
                            autoOpen: false,
                            width: Director.Config.AUTH_LOG_DETAIL ? 900 : 450,
                            height: 600,
                            modal: true,
                            dialogClass: 'alert',
                            open: function () {
                                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                            }
                        });
                        $("#directorLogDiv").dialog("open");
                        $('#logList').jqGrid('setGridParam', {
                            page: 1,
                            datatype: "json",
                            postData: {directorId: entityId}
                        }).trigger('reloadGrid');
                    }
                })
            },
            setTimer: function (start_time, stop_time) {
                var nowTime, endTime, duration;
                var endTime = new Date(start_time); //截止时间
                var stopTime = new Date(stop_time)
                nowTime = new Date();
                if (stopTime.getTime() < nowTime.getTime()) {
                    Director.Model.updateEndMode();
                    Director.Model.stopTimer();
                } else {
                    duration = parseInt(Math.abs(endTime.getTime() - nowTime.getTime()) / 1000);
                    var darArr = [];
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 24);
                    duration = ( duration - duration % 24) / 24;
                    if (duration > 0) {
                        darArr.push(duration);
                    }
                    Director.Model.updateTimeModel(darArr);
                    if (!Director.Config.TIME_COLOR_CHANGE) {
                        if (nowTime.getTime() > endTime.getTime()) {
                            Director.Model.updateRunningMode();
                        }
                    }
                }
            },

            calculateDate: function (str) {//month 7days yestoday today
                var from_date = "", to_date = "";
                var d = new Date();
                var defaultEnd = this.formatDateTimeFormat(d);
                this.setZeroTime(d);
                if (str == "today") {
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd;
                }
                if (str == "yesterday") {
                    d.setDate(d.getDate() - 1);
                    from_date = this.formatDateTimeFormat(d);
                    this.setDayLastTime(d);
                    to_date = this.formatDateTimeFormat(d);
                }

                if (str == "7days") {
                    d.setDate(d.getDate() - 6);
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd
                }
                if (str == "month") {
                    d.setMonth(d.getMonth() - 1);
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd
                }
                this.bindDate("startDate", "endDate", { maxDate: to_date, maxDateTime: new Date(to_date.replace(/-/g, "/")), minDate: from_date, minDateTime: new Date(from_date.replace(/-/g, "/"))})
                $("input[name=startDate]").datetimepicker("setDate", new Date(from_date.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(to_date.replace(/-/g, "/")));
            },
            submitAddSignal: function () {
                var parnet = $("#dlg_add_signal");
                var signalName = parnet.find("input[name=signal_name]").val();
                if (signalName.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号名称不能为空", type: "error"});
                    return false;
                }
                var signalType = parnet.find("select[name=signal_type]").val();
                var signalId = "";
                var signalUrl = "";
                var signalPreviewUrl = "";

                if (signalType == "0" || signalType == "1") {
                    signalId = parnet.find("input[name=signal_url_" + signalType + "]").suggest("getValue");
                    if (signalId.length == 0) {
                        EpgWeb.Plugin.showTips({content: "信号源异常", type: "error"});
                        return false;
                    }

                } else if (signalType == "2") {
                    signalUrl = parnet.find("input[name=signal_url_2]").val();
                    signalPreviewUrl = parnet.find("input[name=preview_url]").val();
                    if (!this.checkValidStreamUrl(signalUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                        EpgWeb.Plugin.showTips({content: "流地址格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                        return false;
                    }
                    if (signalPreviewUrl != "" && !this.checkValidStreamUrl(signalPreviewUrl, Director.Config.REG_VALIDATE.RTMP_ONLY)) {
                        EpgWeb.Plugin.showTips({content: "流预览地址格式错误,需要( rtmp://）", type: "error"});
                        return false;
                    }
                } else {
                    EpgWeb.Plugin.showTips({content: "信号类型异常", type: "error"});
                    return false
                }
                var baseElement = {
                    signalType: signalType,
                    isDefaultBackup: 0,
                    signalId: signalId,
                    signalName: signalName,
                    signalLegoId: 0
                };
                if (baseElement.signalType == "1") {
                    var labelArr = $("label[name=hint-id]").html().split(/:|;/);
                    baseElement.signalLegoId = Number(labelArr[3]);
                }
                if (baseElement.signalType == "2") {
                    baseElement.signalUrl = signalUrl;
                    baseElement.signalPreviewUrl = signalPreviewUrl;
                }


                var responseData = Director.Dao.getDataByName("entity");
                var entity = responseData.data.result[0];
                baseElement.directorId = entity.id;
                baseElement.programQipuId = entity.programQipuId;
                baseElement.isBackup = 0;

                var tempFunc = function () {
                    Director.Dao.addResource(baseElement, function (data) {
                        if (data != null && data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: data.msg});
                            var resourceId = data.data;
                            if (signalType == "0" || signalType == "2") {
                                var setMainResourceFlag = parnet.find("input[name=set_main_resource]:checked").val();
                                if (setMainResourceFlag == "1") {
                                    Director.Dao.setDirectorMainResource({pid: entity.programQipuId, mainResourceId: resourceId}, function (data) {
                                        if (data != null && data.code == "A00000") {
                                            var updateEntity = Director.Util.getEntity();
                                            updateEntity.mainResourceId = resourceId;
                                            Director.Util.getResourceList();
                                        } else {
                                            EpgWeb.Plugin.showTips({content: "主信号源设置失败", type: "error"});
                                        }

                                    });
                                } else {
                                    Director.Util.getResourceList();
                                }
                            } else {
                                Director.Util.getResourceList();
                            }

                        } else {
                            EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        }
                    })
                }
                if (baseElement.signalType == "0") {
                    var qipuId = Number(baseElement.signalId)
                    var options = {
                        url: Director.urlConfig.queryRtmpUrl,
                        dataType: 'json',
                        data: {qipuId: qipuId},
                        type: "get",
                        success: function (data) {
                            if (data != null && data.code == "A00000") {
                                if (data.data.output_url.length > 0) {
                                    tempFunc();
                                } else {
                                    EpgWeb.Plugin.showTips({content: "没有流不能添加", type: "error"});
                                    console.error("submitAddSignal fail")
                                }
                            }
                        },
                        error: function (data) {
                            console.error("submitAddSignal fail")
                        }
                    }
                    $.ajax(options)
                } else {
                    tempFunc();
                }


                return true;
            },
            submitAddBackUp: function () {
                var parnet = $("#dlg_add_alternatePlay")
                var signalId = parnet.find("input[name=signal_url_1]").suggest("getValue");
                var signalName = parnet.find("input[name=signal_name]").val();
                if (signalName.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号名称不能为空", type: "error"});
                    return false;
                }
                if (signalId.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号源异常", type: "error"});
                    return false;
                }
                var baseElement = {
                    signalType: 1,
                    isDefaultBackup: 0,
                    signalId: signalId,
                    signalName: signalName,
                    signalLegoId: 0
                };
                if (baseElement.signalType == "1") {
                    var labelArr = $("label[name=hint-id]").html().split(/:|;/);
                    baseElement.signalLegoId = Number(labelArr[3]);
                }
                if (parnet.find("input[name=default_play]").is(":checked")) {
                    baseElement.isDefaultBackup = 1;
                }

                var responseData = Director.Dao.getDataByName("entity");
                var entity = responseData.data.result[0];
                baseElement.directorId = entity.id;
                baseElement.programQipuId = entity.programQipuId;
                baseElement.isBackup = 1;
                Director.Config.WAITING_MSG = true;
                Director.Dao.addResource(baseElement, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: data.msg});
                        Director.Util.getBackUpList();
                    } else {
                        EpgWeb.Plugin.showTips({content: "添加失败", type: "error"});
                    }
                    Director.Config.WAITING_MSG = false;
                })
                return true;
            },
            makeUpBackUpDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><img class="gou" src="img/u743.png"  data-id="' + element.id + '" onclick="Director.Util.setDefaultBackUp(this)"><span  onclick="Director.Util.delResource( this ) " data-backup="1" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="1" type="text"  value="' + element.signalName + '" data-id="' + element.id + '"  onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)" >');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceType1Div: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><span onclick="Director.Util.delResource(this)" data-backup="0" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="0" type="text"  value="' + element.signalName + '" data-id="' + element.id + '" onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)">');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><img class="gou" src="img/u743.png" title="点击设置主信号源"  data-id="' + element.id + '" onclick="Director.Util.setDirectorMainResource('+ element.id +')"><span   onclick="Director.Util.delResource(this)" data-backup="0" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="0" type="text"  value="' + element.signalName + '" data-id="' + element.id + '" onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)">');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceAddDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div id="resourceAddDiv"  >');
                htmlArr.push(' <div style="background-color: #ffffff;text-align: center"><img id="imgResource"  src="img/addSourceBtn.png" style="margin-top: 30px" onclick="Director.Util.addResource()">');
                htmlArr.push(' <div style="text-align: center;font-size: 14px;color: #b2beca">添加信号源</div> ');
                htmlArr.push('</div>');
                htmlArr.push(' </div>');
                return htmlArr.join("");
            },
            makeUpBackUpAddDiv: function () {
                var htmlArr = [];
                htmlArr.push(' <div id="backUpAddDiv" >');
                htmlArr.push(' <div style="background-color: #ffffff;text-align: center"><img id="imgBackUp" src="img/addSourceBtn.png" style="margin-top: 30px" onclick="Director.Util.addBackUp()">');
                htmlArr.push(' <div style="text-align: center;font-size: 14px;color: #b2beca">添加灾备</div> ');
                htmlArr.push('</div>');
                htmlArr.push(' </div>');
                return htmlArr.join("");
            },

            // type = (1,2,3,4) (图片，字幕，动画，音效)
            makeUpEffectDiv: function (e, type) {
                if (type == 5 && e.name.trim().length == 0) {
                    e.name = "遮标" + e.id;
                }
                var options = encodeURIComponent(JSON.stringify(e));
                var htmlArr = [];
                switch (type) {
                    case 1:
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 1)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <img class="content" src="' + e.url + '">');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="" data-id="' + e.id + '">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 1)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 1)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 1)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            //htmlArr.push(' <span onclick="Director.Util.delEffect(this, ' + e.type + ')" data-id="' + e.id + '">X</span>');
                            htmlArr.push(' <img class="content" src="' + e.url + '">');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        }
                        break;
                    case 2:
                        if (e.url.length > 32) {
                            e.url = e.url.slice(0,32) + ' ...';
                        }
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_subtitle_div" stype="position: relative;">');
                            htmlArr.push(' <span style="float:left;margin-top:8px;">' + e.url + '</span>');
                            htmlArr.push(' <div class="effect_upper"><div class="effect_hint">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 2)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div></div>');
                        } else {
                            htmlArr.push(' <div style="position:relative;" data-div-id="' + e.id + '" data=' + options + ' class="effect_subtitle_div" data-id="' + e.id + '">');
                            htmlArr.push(' <span style="position:absolute;margin-top:8px;">' + e.url + '</span>');
                            htmlArr.push(' <div style="position:absolute;right:0px;margin-top:8px;background:#e7f0f7;">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 2)">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 2)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 2)">');
                            htmlArr.push(' </div></div>');
                        }
                        break;
                    case 3:
                        var extraInfo = e.extraInfo != "" ? JSON.parse(e.extraInfo) : {};
                        var imageUrl = extraInfo['foreground'] || "img/default_animation.png";
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 3)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <img class="content" src="' + imageUrl + '">');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 3)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewAnimationEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 3)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 3)">');
                            htmlArr.push(' <img class="content" src="' + imageUrl + '">');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');

                        }
                        break;
                    case 4:
                        var extraInfo = e.extraInfo != "" ? JSON.parse(e.extraInfo) : {};
                        var volumn = extraInfo['volumn'] || '0';
                        htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_audio_div">');
                        htmlArr.push(' <div style="position: relative;">');
                        htmlArr.push(' <input class="volumn-range" data-id="' + e.id + '" type="range" min="0" max="100" value="' + volumn + '" onchange="Director.Util.changeVolumn(this)"/>')
                        htmlArr.push(' <button class="d-btn d-btn-primary play" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 4)">播出</button>');
                        //htmlArr.push(' <img class="change" src="img/u128.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 4)">');
                        //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                        htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 4)">');
                        htmlArr.push(' <img class="content" src="img/default_audio.png">');
                        htmlArr.push(' </div>');
                        //htmlArr.push(' <input class="volumn-range" data-id="' + e.id + '" type="range" min="0" max="100" value="' + volumn + '" onchange="Director.Util.changeVolumn(this)" style="margin-bottom: 10px;width:164px;" />')
                        htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                        htmlArr.push(' </div>');
                        break;
                    case 5:
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 5)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            if (e.url.trim().length >0) {
                                htmlArr.push(' <img class="content" src="' + e.url + '">');
                            }else{
                                htmlArr.push(' <img class="content" src="img/director/effect_cover.png">');
                            }
                            htmlArr.push(' </div>')
                            if (e.name.trim().length >0) {
                                htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }else{
                                htmlArr.push(' <input type="text" value="遮标' + e.id + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="" data-id="' + e.id + '">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 5)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 5)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 5)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            //htmlArr.push(' <span onclick="Director.Util.delEffect(this, ' + e.type + ')" data-id="' + e.id + '">X</span>');
                            if (e.url.trim().length >0) {
                                htmlArr.push(' <img class="content" src="' + e.url + '">');
                            }else{
                                htmlArr.push(' <img class="content" src="img/director/effect_cover.png">');
                            }
                            htmlArr.push(' </div>');
                            if (e.name.trim().length >0) {
                                htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }else{
                                htmlArr.push(' <input type="text" value="遮标' + e.id + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }

                            htmlArr.push(' </div>');
                        }
                        break;

                }

                return htmlArr.join("");
            },

            makeUpEffectAddDiv: function(type) {
                var htmlArr = [];
                switch (type) {
                    case 1:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label for="effect_img_file_input">');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png">');
                        htmlArr.push('</label>');
                        htmlArr.push('<input id="effect_img_file_input" type="file" style="display:none" class="uploadBtn"/>')
                        htmlArr.push('</div></div>');
                        break;
                    case 3:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label>');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png" onclick="Director.Util.AddAnimationShow();">');
                        htmlArr.push('</label>');
                        htmlArr.push('</div></div>');
                        break;
                    case 4:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label for="effect_audio_file_input">');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png">');
                        htmlArr.push('</label>');
                        htmlArr.push('<input id="effect_audio_file_input" type="file" style="display:none" class="uploadBtn" accept="audio/mpeg"/>')
                        htmlArr.push('</div></div>');
                        break;
                    case 5:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label>');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png" onclick="Director.Util.AddCoverShow();">');
                        htmlArr.push('</label>');
                        htmlArr.push('</div></div>');
                        break;

                }

                return htmlArr.join("");
            },

            reloadListHandler: function (data) {
                if (data != null) {
                    EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                    if (data.code == "A00000") {
                        $("#list").trigger("reloadGrid")
                    }
                } else {
                    console.log("callbackHandler no return data");
                }
            },
            submitEditDirector: function () {
                var parent = $("#dlg_settings");
                var rtmpUrl = parent.find("input[name=input_out_url]").val();
                var delayTime = parent.find("input[name=delay]").val();
                var streamType = parent.find("select[name=stream_type]").val();
                if (!this.checkValidStreamUrl(rtmpUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                    EpgWeb.Plugin.showTips({content: "流格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                    return;
                }
                if (isNaN(delayTime) || parseInt(delayTime) < 0 || parseInt(delayTime) > 30) {
                    EpgWeb.Plugin.showTips({content: "延时时间范围为0~30秒", type: "error"});
                    return;
                }
                var oldEntity = Director.Util.getEntity();

                var newData = $.extend({}, oldEntity);
                newData.outputUrl = rtmpUrl;
                newData.delay = delayTime;
                newData.outputStreamType = streamType;

                Director.Config.DURING_CHANGE_SETTINGS = true;
                Director.Dao.editDirector({entity: JSON.stringify(newData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: "修改导播台成功"});
                        oldEntity.outputUrl = newData.outputUrl;
                        oldEntity.delay = newData.delay;
                        oldEntity.outputStreamType = newData.outputStreamType;
                        Director.Util.initDetailZone(oldEntity);

                        Director.Commentary.checkCommentaryAfterEditDirector();
                        setTimeout("Director.Util.notifyUpdateDirector('" + JSON.stringify(newData) + "')", 3000);
                    } else {
                        EpgWeb.Plugin.showTips({content: "修改导播台失败", type: "error"});
                    }
                    Director.Config.DURING_CHANGE_SETTINGS = false;
                });
            },

            notifyUpdateDirector: function(entity) {
                var data = JSON.parse(entity);

                var request = {};

                request.type = 'post';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'updateprogram' + "?PID=" + data.programQipuId;

                var beginTime = new Date(data.startPlayTime);
                var endTime = new Date(data.stopPlayTime);

                request.params = {
                    ID : parseInt(data.programQipuId),
                    NAME : data.programName,
                    ADDRESS : data.outputUrl,
                    DELAY: parseInt(data.delay),
                    RESOLUTION: data.outputStreamType,
                    BEGINTIME: parseInt(beginTime.getTime()/1000),
                    ENDTIME: parseInt(endTime.getTime()/1000),
                    UPDATEBY: '_system_',
                    MAINSOURCE: data.mainResourceId==0 ? "" : data.mainResourceId
                };

                request.params = JSON.stringify(request.params);

                request.directorId = data.id;
                request.logType = "102";
                request.raw = 1;

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {

                    //self.callback(options);
                })
            },

            submitEditEffect: function (type) {
                var self = this;
                self.type = type;
                var extraInfo = "";
                var location = '';
                var id = '';
                var entity = self.getEntity();
                var url = '';
                var updateData = {};

                switch (type) {
                    case 1:
                        var parent = $("#dlg_edit_image");
                        var params = self.getParams(parent);
                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }

                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        var size = {};
                        id = params['id'];
                        size.w = params['size_w'];
                        size.h = params['size_h'];
                        extraInfo.size = JSON.stringify(size);

                        // remove unnecessary params
                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['size_w'];
                        delete extraInfo['size_h'];
                        delete extraInfo.id;

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };

                        var parent = $('#tabPanel_3');
                        var curDiv = parent.find("div[data-div-id=" + id + "]");
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        options.location = location
                        options.extraInfo = extraInfo

                        self.notifyFlashEditEffect(JSON.stringify(options));

                        //console.log(params);
                        break;
                    case 2:
                        var parent = $("#dlg_edit_subtitle");
                        var params = self.getParams(parent);

                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }

                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        id = params['id'];
                        url = params['content'];

                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['id'];
                        delete extraInfo['content'];

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            url: url,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };


                        if (id != '') {
                            var parent = $('#tabPanel_3');
                            var curDiv = parent.find("div[data-div-id=" + id + "]");
                            var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                            options.location = location;
                            options.extraInfo = extraInfo;
                            options.url = url;

                            self.notifyFlashEditEffect(JSON.stringify(options));
                        }
                        break;
                    case 3:
                        var parent = $('#dlg_edit_animation');
                        var params = self.getParams(parent);

                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }
                        extraInfo = params;
                        id = params['id'];
                        url = params['url'];

                        delete extraInfo.myname;

                        extraInfo = JSON.stringify(extraInfo);
                        console.log(params);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };
                        break;
                    case 5:
                        var parent = $("#dlg_edit_cover");
                        var params = self.getParams(parent);
                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }
                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        var size = {};
                        id = params['id'];
                        size.w = params['size_w'];
                        size.h = params['size_h'];
                        extraInfo.size = JSON.stringify(size);
                        url = "http://jyyunlou7.oss.qiyi.storage:8080/v1/AUTH_becf1c9cf362414992517833e5128e4e/20180103-05/yunpan/20180103/11/88/e009679b12974a11bfedc3638604f7b1.png";
                        // remove unnecessary params
                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['size_w'];
                        delete extraInfo['size_h'];
                        delete extraInfo.id;

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };

                        if (id != '') {
                            var parent = $('#tabPanel_3');
                            var curDiv = parent.find("div[data-div-id=" + id + "]");
                            var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                            options.location = location;
                            options.extraInfo = extraInfo;
                            options.url = url;

                            self.notifyFlashEditEffect(JSON.stringify(options));
                        }

                        //console.log(params);
                        break;

                }

                if (id != '') {

                    Director.Dao.editEffect(updateData, function (data) {
                        if (data != null && data.code == "A00000") {
                            //EpgWeb.Plugin.showTips({content: "修改成功"});
                            self.refreshEffectList(self.type);
                        }
                    });

                } else {
                    var element = {};
                    element.directorId = entity.id;
                    element.programQipuId = entity.programQipuId;
                    element.url = url;
                    element.type = type;
                    element.location = location;
                    element.extraInfo = extraInfo;
                    if (type == 3) {
                        var parent = $('#dlg_edit_animation');
                        element.name = parent.find('input[name=myname]').val();

                    } else {
                        element.name = '';
                    }
                    element = JSON.stringify(element);

                    Director.Dao.addEffect({'data': element}, function (data) {
                        if (data != null && data.code == "A00000") {
                            Director.Util.refreshEffectList(type);
                        }
                    })
                }

                return true;
            },

            getParams: function (obj) {
                var self = this;
                var params = {};

                var $form = obj.find('form[name="basicForm"]');
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $form.find('input[name="' + name + '"]:checked').val() || '';
                        } else if (this.type == 'checkbox') {
                            params[name] = $form.find('input[name="' + name + '"]').is(":checked") ? 1 : 0;
                        } else {
                            var value = $.trim($(this).val());
                            if (value == "0") {
                                params[name] = 0;
                            } else {
                                params[name] = parseInt(value) || value || '';
                            }

                        }
                    }

                });

                //params['id'] = $form.find('input[name=id]').val();

                console.log(params);

                return params;
            },

            checkValidStreamUrl: function (streamUrl, regRule) {
                return regRule.test(streamUrl)
            },
            updateResourceTitle: function (element) {
                var oldEntity = Director.Util.getEntity();
                var $input = $(element);
                var elementId = $input.attr("data-id");
                var isBackUp = $input.attr("data-backup") == "1";
                var pageBean = isBackUp ? Director.Config.PageBeanBackup : Director.Config.PageBeanResource;
                var signalName = $input.val().trim();
                var rowData = pageBean.findData("id", parseInt(elementId));
                if (signalName.length > 0) {
                    if (rowData.signalName == signalName) {
                        return;
                    }
                    Director.Dao.editResource({ id: elementId, signalName: signalName, directorId: oldEntity.id }, function (data) {
                        if (data != null && data.code == "A00000") {
                            //EpgWeb.Plugin.showTips({content: isBackUp ? "修改灾备成功" : "修改导播台资源成功"});
                            var rowData = pageBean.findData("id", parseInt(elementId));
                            rowData.signalName = $input.val().trim();
                            $input.val(signalName);
                        } else {
                            EpgWeb.Plugin.showTips({content: isBackUp ? "修改灾备失败" : "修改导播资源失败", type: "error"});
                        }
                    })
                } else {
                    $input.val(rowData.signalName);
                }
            },
            updateResourceTitleShortCut: function (event) {
                if (event.keyCode == 13) {
                    $(event.currentTarget).blur();
                }
            },

            updateEffectName: function (e) {
                var self = this;
                var entity = self.getEntity();
                var $input = $(e);
                var eid = $input.attr("data-id");
                var name = $input.val().trim();
                //重设data.name ,以便flash实时更新
                var $effectElement = $input.parent(".effect_element_div");
                var options = decodeURIComponent($effectElement.attr("data"));
                var optionsObject = JSON.parse(options);
                optionsObject.name = name;
                $effectElement.attr("data", encodeURIComponent(JSON.stringify(optionsObject)));

                Director.Dao.editEffect({id: eid, name: name, directorId: entity.id}, function (data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "修改成功"});
                        //self.refreshEffectList(self.type);
                    }
                });
            },

            updateEffectNameShortCut: function (event) {
                if (event.keyCode == 13) {
                    $(event.currentTarget).blur();
                }
            },

            delResource: function (element) {
                var entity = this.getEntity();
                var sendData = {id: $(element).attr("data-id"), directorId: entity.id };
                var isBackUp = $(element).attr("data-backup") == "1";
                SystemDialog.queryConfirm("确认要删除么？", function (flag) {
                    if (flag === true) {
                        Director.Dao.delResource(sendData, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: isBackUp ? "删除灾备成功" : "删除导播台资源成功"});
                                if (isBackUp) {
                                    Director.Util.getBackUpList();
                                } else {
                                    Director.Util.getResourceList();
                                }
                            } else {
                                var result = "";
                                if (data != null) {
                                    if (data.data != null) {
                                        result = Director.Config.HINT_MSG["" + data.data];
                                        if (result == null) {
                                            result = '';
                                        }
                                    }
                                }
                                EpgWeb.Plugin.showTips({content: (isBackUp ? "删除灾备失败" : "删除导播资源失败") + (result.length > 0 ? "," + result : ""), type: "error"});
                            }
                        })
                    }
                })
            },

            delEffect: function (element, type) {
                var self = this;
                var entity = this.getEntity();
                var eid = $(element).attr("data-id");
                var sendData = {id: eid, directorId: entity.id};

                self.sendData = sendData;
                self.type = type;
                SystemDialog.queryConfirm("确定要删除么？", function (flag) {
                    if (flag === true) {
                        if (type == "4") {
                            var request = {};

                            request.type = 'get';
                            request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stopplay';
                            request.params = {
                                ID: eid,
                                PID: entity.programQipuId
                            };
                            request = JSON.stringify(request);
                            Ancestor.Dao.redirectRequest({request: request}, function (data) {
                                if (data != null && data.error_code == "A00000") {
                                    self.submitDelEffect(self.sendData, self.type);
                                } else {
                                    EpgWeb.Plugin.showTips({content: "删除失败 " + JSON.stringify(data), type: "error"});
                                }
                            });
                        } else if (type == "1" || type == "2" ||type == "5" ) {
                            var request = {};

                            request.type = 'get';
                            request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                            request.params = {
                                ID: eid,
                                PID: entity.programQipuId
                            };
                            request = JSON.stringify(request);
                            Ancestor.Dao.redirectRequest({request: request}, function (data) {
                                if (data != null && data.error_code == "A00000") {
                                    Director.Player.removeEffect(self.sendData.id);
                                    self.submitDelEffect(self.sendData, self.type);
                                } else {
                                    EpgWeb.Plugin.showTips({content: "删除失败 " + JSON.stringify(json), type: "error"});
                                }
                            });
                        } else {

                            Director.Dao.deleteEffect(sendData, function (data) {
                                if (data != null && data.code == "A00000") {
                                    EpgWeb.Plugin.showTips({content: "删除成功"});
                                    self.refreshEffectList(type);
                                } else {
                                    var result = '';
                                    if (data != null) {
                                        result = Director.Config.HINT_MSG["" + data.data];
                                        if (result == null) {
                                            result = '';
                                        }
                                    }
                                    EpgWeb.Plugin.showTips({content: "删除失败", type: "error"});
                                }
                            })
                        }
                    }
                })
            },

            submitDelEffect: function (sendData, type) {
                var self = this;
                Director.Dao.deleteEffect(sendData, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: "删除成功"});
                        self.refreshEffectList(type);
                    } else {
                        var result = '';
                        if (data != null) {
                            result = Director.Config.HINT_MSG["" + data.data];
                            if (result == null) {
                                result = '';
                            }
                        }
                        EpgWeb.Plugin.showTips({content: "删除失败", type: "error"});
                    }
                })
            },

            setDefaultBackUp: function (element) {
                var oldEntity = Director.Util.getEntity();
                var elementId = $(element).attr("data-id");
                var elementData = Director.Config.PageBeanBackup.findData("id", parseInt(elementId));
                SystemDialog.queryConfirm("确认要设为默认灾备么？", function (flag) {
                    if (flag === true) {
                        Director.Config.WAITING_MSG = true;
                        Director.Dao.editResource({id: elementData.id, isDefaultBackup: 1, directorId: oldEntity.id}, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: "设置成功"});
                                Director.Util.getBackUpList();
                            } else {
                                EpgWeb.Plugin.showTips({content: "设置失败", type: "error"});
                            }
                            Director.Config.WAITING_MSG = false;
                        })
                    }
                })
            },

            addBackUp: function () {
                var parent = $("#dlg_add_alternatePlay");
                parent.dialog("open");
                parent.find("label[name=hint-id]").html();
                var index = Director.Config.PageBeanBackup.getSource().length + 1;
                parent.find("input[name=signal_name]").val("备播视频" + index);
                if (parent.find("input[name=default_play]").is(":checked")) {
                    parent.find("input[name=default_play]").click();
                }
                parent.find("input[name=signal_url_1]").suggest("setValue", "");
            },
            addResource: function () {
                var parent = $("#dlg_add_signal");
                parent.dialog("open");
                parent.find("label[name=hint-id]").html();
                parent.find("select[name=signal_type]").change();
                var index = Director.Config.PageBeanResource.getSource().length + 1;
                parent.find("input[name=signal_name]").val("信号源" + index);
                parent.find("input[name=signal_url_2]").val("");
                parent.find("input[name=signal_url_0]").suggest("setValue", "");
                parent.find("input[name=signal_url_1]").suggest("setValue", "");
                parent.find("input[name=preview_url]").val("");
            },

            addEffect: function (element) {
                var self = this;
                var entity = self.getEntity();
                var params = element;
                params.directorId = entity.id;

                Director.Dao.addEffect(params, function (data) {
                    if (data != null && data.code == "A00000") {

                    }
                })
            },

            editEffectShow: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var parent = $('#tabPanel_3');
                var curDiv = parent.find("div[data-div-id=" + eid + "]");

                switch (type) {
                    case 1:
                        var parent = $("#dlg_edit_image");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        extra.id = options.id;

                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        if (extra.hasOwnProperty('size') && extra['size'] != '') {
                            var size = JSON.parse(extra.size);
                            extra.size_w = size.w;
                            extra.size_h = size.h;
                        }

                        parent.dialog("open");

                        parent.find('input[name=id]').val(eid);

                        $.each($elements, function () {
                            name = this.name;

                            var e = $(this);
                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else if (options.extraInfo == "" && e.attr("data-default")) {
                                    e.val(e.attr('data-default'));
                                } else {
                                    if (extra[name] === 0) {
                                        e.val(0);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-image-loop-div').show();
                        } else {
                            $form.find('#effect-image-loop-div').hide();
                        }

                        $form.find('select[name=animation]').change();

                        break;
                    case 2:
                        var parent = $("#dlg_edit_subtitle");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        extra.content = options.url;


                        parent.dialog('option', 'title', '字幕编辑').dialog("open");

                        parent.find('input[name=id]').val(eid);
                        parent.find('textarea[name=content]').val(options.url);

                        $.each($elements, function () {
                            name = this.name;
                            var e = $(this);

                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else {
                                    if (extra[name] == "0") {
                                        e.val(extra[name]);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        var fontElements = ['fontBold'];
                        $.each(fontElements, function (index, e) {
                            if (extra[e] == "1") {
                                $form.find('a.' + e).addClass('active');
                            } else {
                                $form.find('a.' + e).removeClass('active');
                            }

                            //var d = $form.find('a.' + e);
                            //var $input = $form.find('input.' + e);
                            //d.bind('click',{d: d, input: $input}, function(event) {
                            //    if (event.data.d.hasClass('active')) {
                            //        event.data.d.removeClass('active');
                            //        event.data.input.val(0);
                            //    }else{
                            //        event.data.d.addClass('active');
                            //        event.data.input.val(1);
                            //    }
                            //})
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-subtitle-loop-div').show();
                        } else {
                            $form.find('#effect-subtitle-loop-div').hide();
                        }

                        if ($form.find('input[name=horseLamp]').is(":checked")) {
                            $form.find('#effect-subtitle-loop-container-div').show();
                        } else {
                            $form.find('#effect-subtitle-loop-container-div').hide();
                        }

                        Director.Util.dialogSubtitlePreview();

                        break;
                    case 3:
                        var parent = $("#dlg_edit_animation");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};
                        parent.dialog('option', 'title', '编辑').dialog("open");

                        parent.find('input[name=id]').val(eid);
                        parent.find('div#form_animation_url').hide();

                        $.each($elements, function () {
                            name = this.name;
                            var e = $(this);

                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else {
                                    if (extra[name] == "0") {
                                        e.val(extra[name]);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-animation-loop-div').show();
                        } else {
                            $form.find('#effect-animation-loop-div').hide();
                        }
                        break;
                    case 5:
                        var parent = $("#dlg_edit_cover");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        console.log("elements: " + JSON.stringify($elements));
                        extra.id = options.id;
                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        if (extra.hasOwnProperty('size') && extra['size'] != '') {
                            var size = JSON.parse(extra.size);
                            extra.size_w = size.w;
                            extra.size_h = size.h;
                        }
                        parent.dialog("open");
                        parent.find('input[name=id]').val(eid);
                        $.each($elements, function () {
                            name = this.name;

                            var e = $(this);
                            if (name) {
                                if (extra[name] === 0) {
                                    e.val(0);
                                } else {
                                    e.val(extra[name] || '');
                                }
                            }
                        });
                        break;

                }
            },

            AddSubtitleBackground: function (data, params) {
                var parent = $("#dlg_edit_subtitle");
                var $background = parent.find('input[name=background]');
                $background.val(data.httpInnerUrl);
            },

            AddAnimationUrl: function (data, params) {
                var parent = $("#dlg_edit_animation");
                var $background = parent.find('input[name=url]');
                var myname = parent.find('input[name=myname]');
                $background.val(data.httpInnerUrl);
                myname.val(params.file.name);
            },

            clearForm: function (form) {
                var $form = form;
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                //var fontElements = ['fontBold', 'fontItalic', 'fontUnderline'];
                var fontElements = ['fontBold'];

                $form.find('input[name=id]').val('');
                $form.find('textarea[name=content]').val('');

                $.each($elements, function () {
                    name = this.name;

                    var e = $(this);
                    if (name) {
                        if (this.type == 'checkbox') {
                            e.prop("checked", false);
                        } else if (name == "id") {

                        } else if (e.attr("data-default")) {
                            e.val(e.attr('data-default'));
                        } else {
                            e.val('');
                        }
                    }

                    if ($.inArray(name, fontElements) != -1) {
                        $form.find('a.' + name).removeClass('active');
                    }
                    ;


                });

            },

            AddAnimationForeground: function (data, params) {
                var parent = $("#dlg_edit_animation");
                var $background = parent.find('input[name=foreground]');
                $background.val(data.httpInnerUrl);
            },

            AddSubtitleShow: function () {
                var self = this;
                var parent = $("#dlg_edit_subtitle");
                var $form = parent.find('form[name="basicForm"]');
                self.clearForm($form);
                parent.dialog('option', 'title', '添加字幕').dialog("open");


                if ($form.find('input[name=loop]').is(":checked")) {
                    $form.find('#effect-subtitle-loop-div').show();
                } else {
                    $form.find('#effect-subtitle-loop-div').hide();
                }

                if ($form.find('input[name=horseLamp]').is(":checked")) {
                    $form.find('#effect-subtitle-loop-container-div').show();
                } else {
                    $form.find('#effect-subtitle-loop-container-div').hide();
                }

                $form.find('select[name=fontSize]').val("15");


                Director.Util.dialogSubtitlePreview();
            },

            AddAnimationShow: function () {
                var self = this;
                var parent = $("#dlg_edit_animation");
                var $form = parent.find('form[name="basicForm"]');
                self.clearForm($form);
                parent.dialog('option', 'title', '添加动画').dialog("open");

                $form.find('#form_animation_url').show();

                if ($form.find('input[name=loop]').is(":checked")) {
                    $form.find('#effect-animation-loop-div').show();
                } else {
                    $form.find('#effect-animation-loop-div').hide();
                }
            },
            AddCoverShow: function () {
                var self = this;
                //获取当前数据是否大于最大数量8
                var effectCoversLength = $("#effect-covers").children().length -1;
                if (effectCoversLength >= 8) {
                    EpgWeb.Plugin.showTips({content: "最多同时支持8个遮标", type: "error"});
                }else{
                    var parent = $("#dlg_edit_cover");
                    var $form = parent.find('form[name="basicForm"]');
                    self.clearForm($form);
                    parent.dialog('option', 'title', '遮标编辑').dialog("open");
                }


            },

            startUploadFile: function (params, callback) {
                var self = this;
                var url = Director.Config.EFFECT_UPLOAD_URL;
                url = url + "?t=1";

                $.each(params, function (k, v) {
                    url = url + "&" + k + "=" + v;
                });

                $.ajax({
                    url: url,
                    method: "post",
                    cache: false,
                    contentType: false,
                    processData: false,
                    xhr: function () {
                        var xhr = jQuery.ajaxSettings.xhr();
                        return xhr;
                    },
                    data: params.file,
                    success: function (data) {
                        if (data.code == "A00000") {
                            console.log("success upload");
                            callback.call(this, data.data, params);
                        }
                    },
                    error: function (data) {

                    }
                })
            },

            getEntity: function () {
                var responseData = Director.Dao.getDataByName("entity");
                if (responseData == null || responseData.data == null || responseData.data.totalCount == 0) {
                    return null;
                }
                return responseData.data.result[0];
            },
            reloadEntity: function (needNotify) {
                var self = this;
                var entity = self.getEntity();
                Director.Dao.getDirector({qipuId: entity.programQipuId, fullMode: "true"}, function (data) {
                    if (data != null && data.code == "A00000") {
                        if (data.data.result.length == 1) {
                            Director.Util.updateEntity(data);
                            entity = self.getEntity();
                            console.log(" reloadEntity :" + JSON.stringify(entity));
                            Director.Player.setCurResourceId(entity.resourceId);
                            if (needNotify) {
                                Director.Player.notifyPlayingChange();
                            }
                        }
                    }
                });
            },
            updateEntity: function (newResponse) {
                EpgWeb.ajaxQueue.removeTask("entity");
                EpgWeb.ajaxQueue.push("entity", null, newResponse);
                console.log("更新 entity 完成数据");
            },
            preSetMainResource: function (resourceList) {
                var self = this;
                var entity = self.getEntity();
                $.each(resourceList, function (i, element) {
                    if (element.signalType == 0 || element.signalType == 2) {
                        if(element.id == entity.mainResourceId) {
                            element.isMainResource = true;
                        } else {
                            element.isMainResource = false;
                        }
                    }
                });
            },
            getResourceList: function () {
                var entity = this.getEntity();
                var self = this;
                Director.Dao.getResourceList({directorId: entity.id, isBackup: 0}, function (data) {
                    Director.Config.PageBeanResource.setNewData([], 10);
                    if (data != null && data.code == "A00000") {
                        self.preSetMainResource(data.data);
                        Director.Config.PageBeanResource.setNewData(data.data);
                        Director.Player.registerResource(data.data);
                    }
                })
            },
            getBackUpList: function (autoHandler) {
                var entity = this.getEntity();
                var self = this;
                Director.Dao.getResourceList({directorId: entity.id, isBackup: 1}, function (data) {
                    Director.Config.PageBeanBackup.setNewData([], 10);
                    if (data != null && data.code == "A00000") {
                        Director.Config.PageBeanBackup.setNewData(data.data)
                        Director.Player.registerBackup(data.data);
                    }
                })
            },


            getEffectList: function (type) {
                var self = this;
                var entity = this.getEntity();

                Director.Dao.getEffectList({directorId: entity.id, type: type}, function (data) {
                    if (data != null && data.code == "A00000") {
                        self.makeEffectList(type, data.data);

                        switch (type) {
                            case 1:
                                Director.Config.PageBeanEffectImage.setNewData(data.data);
                                Director.Util.bindEffectImageEvent();
                                break;
                            case 2:
                                Director.Config.PageBeanEffectSubtitle.setNewData(data.data);
                                break;
                            case 3:
                                Director.Config.PageBeanEffectAnimation.setNewData(data.data);
                                break;
                            case 4:
                                Director.Config.PageBeanEffectAudio.setNewData(data.data);
                                Director.Util.bindEffectAudioEvent();
                                break;
                            case 5:
                                Director.Config.PageBeanEffectCover.setNewData(data.data);
                                break;

                        }
                    }
                })

            },

            makeEffectList: function (type, data) {
                var self = this;

                var container = null,
                    content = "";

                var htmlArr = [];

                switch (type) {
                    case 1:
                        container = $("#effect-images");
                        break;
                    case 2:
                        container = $("#effect-subtitles");
                        break;
                    case 3:
                        container = $("#effect-animations");
                        break;
                    case 4:
                        container = $("#effect-audios");
                        break;
                    case 5:
                        container = $("#effect-covers");
                        break;

                }
                if(type == 5) {
                    $.each(data, function (index, e) {
                        htmlArr.unshift(self.makeUpEffectDiv(e, type));
                    });
                }else{

                    $.each(data, function (index, e) {
                        htmlArr.push(self.makeUpEffectDiv(e, type));
                    });
                }

                htmlArr.push(self.makeUpEffectAddDiv(type));

                content = htmlArr.join('');

                container.html(content);
            },

            refreshEffectList: function (type) {
                var self = this;

                //switch (type) {
                //    case 1:
                //        $("#effect-images").html('');
                //        break;
                //    case 2:
                //        $("#effect-subtitles").html('');
                //        break;
                //    case 3:
                //        $("#effect-animations").html('');
                //        break;
                //    case 4:
                //        $("#effect-audios").html('');
                //        break;
                //}

                self.getEffectList(type);
            },

            initDefaultBackupZone: function () {
                var self = this;
                var htmlArr = [];
                htmlArr.push(self.makeUpBackUpAddDiv());
                $("#tabPanel_child_2").html(htmlArr.join(""));
            },
            initDefaultResourceZone: function () {
                var self = this;
                var htmlArr = [];
                htmlArr.push(self.makeUpResourceAddDiv());
                $("#tabPanel_child_1").html(htmlArr.join(""));
            },

            initDetailZone: function (entity) {
                Director.Model.initDetail(entity)
            },

            doResourceSwitch: function (resourceId, time, playCounts) {
                var entity = Director.Util.getEntity();
                Director.Dao.switchResource({id: resourceId, directorId: entity.id, time: time, playCounts: playCounts}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.reloadEntity(true);
                    } else if (data != null && data.code == "A00001") {
                        EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        Director.Util.reloadEntity(false);
                    }
                })
            },
            switchBackUp: function () {
                if (Director.Config.WAITING_MSG) {
                    SystemDialog.queryAlert("正在处理中，请稍后操作");
                    return;
                }
                var btnTarget = $("button[name=changeBtn]");
                btnTarget.prop("disabled", "disabled");
                var entity = Director.Util.getEntity();
                if (entity != null) {
                    Director.Config.WAITING_MSG = true;
                    Director.Dao.switchBackUp({directorId: entity.id}, function (data) {
                        if (data != null && data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: "切换成功"});
                            Director.Dao.cfgName.oldDelay = entity.delay;
                            Director.Util.reloadEntity(true);
//                            btnTarget.attr("data-key", "recoverDelay");
//                            btnTarget.html("恢复延时");
                        } else {
                            var msgPlus = null;
                            if (data != null && data.msg != null) {
                                msgPlus = data.msg
                            }
                            EpgWeb.Plugin.showTips({content: "切换失败;" + msgPlus, type: "error"});
                        }
                        btnTarget.removeAttr("disabled", "disabled");
                        Director.Config.WAITING_MSG = false;
                    });
                }
            },
//            recoverDelay: function () {
//                var btnTarget = $("button[name=changeBtn]");
//                btnTarget.prop("disabled", "disabled");
//                var entity = Director.Util.getEntity();
//                if (Director.Dao.cfgName.oldDelay > 0 && Director.Dao.cfgName.oldDelay != entity.delay) {
//                    var newData = $.extend({}, entity)
//                    newData.delay = Director.Dao.cfgName.oldDelay;
//                    Director.Dao.editDirector({entity: JSON.stringify(newData)}, function (data) {
//                        if (data != null && data.code == "A00000") {
//                            EpgWeb.Plugin.showTips({content: "恢复延时成功"});
//                            Director.Util.reloadEntity(false);
//                            Director.Dao.cfgName.oldDelay = -1;
//                            btnTarget.attr("data-key", "switchBackUp");
//                            btnTarget.html("切换灾备");
//                        } else {
//                            var msgPlus = null;
//                            if (data != null && data.msg != null) {
//                                msgPlus = data.msg
//                            }
//                            EpgWeb.Plugin.showTips({content: "恢复延时失败;" + msgPlus, type: "error"});
//                        }
//                        btnTarget.removeAttr("disabled", "disabled");
//                    });
//                } else {
//                    btnTarget.attr("data-key", "switchBackUp");
//                    btnTarget.html("切换灾备");
//                    btnTarget.removeAttr("disabled", "disabled");
//                }
//            },
            changeTab: function (element, cur) {
                var elementDom = $(element);
                if (elementDom.hasClass("selected")) {
                    return;
                }
                $("#tabsDiv").find("li").removeClass("selected").addClass("unselected");
                $("#tabsDiv").find("a").removeClass("selected").addClass("unselected");
                elementDom.removeClass("unselected").addClass("selected");
                elementDom.parent().removeClass("unselected").addClass("selected");

                var refIds = elementDom.attr("data-id").split(",");
                $("#" + refIds[0]).css({zIndex: 1, top: 0, left: 0});
                $("#" + refIds[1]).css({zIndex: -8, top: "-1999px", left: "-1999px"});
                $("#" + refIds[2]).css({zIndex: -9, top: "-2999px", left: "-2999px"});
                $("#" + refIds[3]).css({zIndex: -10, top: "-3999px", left: "-3999px"});

                var toPlayArr = $("#" + refIds[0]).find("object");
                var toStopArr = $("#" + refIds[1]).find("object");
                var toStopArr2 = $("#" + refIds[2]).find("object");
                var toStopArr3 = $("#" + refIds[3]).find("object");

                if (toPlayArr.length > 0 && refIds[0] != "tabPanel_3") {
                    $.each(toPlayArr, function (i, flashPlayer) {
                        Director.Player.recoverVol(flashPlayer.id);
                    })
                }
                if (toStopArr.length > 0 && refIds[1] != "tabPanel_3") {
                    $.each(toStopArr, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }
                if (toStopArr2.length > 0 && refIds[2] != "tabPanel_3") {
                    $.each(toStopArr2, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }
                if (toStopArr3.length > 0 && refIds[3] != "tabPanel_3") {
                    $.each(toStopArr2, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }

                if (refIds[0] == "tabPanel_4") {
                    Director.Commentary.refreshCommentaryList(false);
                }else{
                    Director.Commentary.clearCommentaryList();
                }
            },
//            releaseAllDirector: function () {
//                var entity = Director.Util.getEntity();
//                if (entity != null) {
//                    Director.Dao.releaseAllDirector({directorId: entity.id}, function (data) {
//                        if (data != null && data.code == "A00000") {
//                            EpgWeb.Plugin.showTips({content: "releaseAllDirector 成功"});
//                            setTimeout(function () {
//                                window.location.href = "/epg/program_director_list.html";
//                            }, 1500)
//                        } else {
//                            EpgWeb.Plugin.showTips({content: "releaseAllDirector 失败", type: "error"});
//                        }
//                    })
//                }
//            },
            delDirector: function (directorId) {
                SystemDialog.queryConfirm("确认要删除么？", function (flag) {
                    if (flag === true) {
                        Director.Dao.releaseAllDirector({directorId: directorId}, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: "删除 成功"});
                                $("#list").trigger('reloadGrid');
                            } else {
                                EpgWeb.Plugin.showTips({content: "删除 失败", type: "error"});
                            }
                        })
                    }
                })
            },

            showToolTip: function (element) {
                if (element.value.length > 0) {
                    element.title = element.value;
                }
            },
            resizeTextWidth: function (text, maxLength) {
                var spanTarget = $("span[name=adjTextLength]");

                spanTarget.html(text);
                var newLength = parseInt(text.length * maxLength / spanTarget.width());
                spanTarget.html(text.substring(0, newLength) + "...");
                while (spanTarget.width() > maxLength) {
                    newLength--;
                    spanTarget.html(text.substring(0, newLength) + "...");
                }
                return spanTarget.html();
            },
            showTipsResourceId: function (element) {
                element.title = "资源ID:" + $(element).attr("data-id");
            },

            changeVolumn: function (element) {
                var self = this;
                var volumn = $(element).val();
                var extraInfo = {};
                var entity = self.getEntity();
                if (volumn == "0") {
                    extraInfo.volumn = 0;
                } else {
                    extraInfo.volumn = parseInt(volumn) || volumn;
                }
                extraInfo = JSON.stringify(extraInfo);

                var id = $(element).attr('data-id');
                Director.Dao.editEffect({id: id, extraInfo: extraInfo, directorId: entity.id}, function(data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "修改成功"});
                    }
                })
            },
            changeColor: function (e) {
                console.log(e.value);
            },

            playEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();

                if (Director.Config.EFFECT_CTRL_KEYDOWN) {
                    console.log(eid + " ctrl");
                    Director.Dao.editEffect({id: eid, directorId: entity.id, status: "1"}, function (data) {
                        self.refreshEffectList(type);
                    })

                } else {
                    console.log(eid + " click");
                }
            },

            submitPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();
                var options = {};

                options.eid = eid;
                options.pid = entity.programQipuId;
                options.type = type;
                options.status = "1";
                options.did = entity.id;

                if (type == 4) {
                    self.notifyStopPlayEffect(options, function (options) {
                        setTimeout(function () {
                            self.notifyPlayEffect(options, self.saveEffectStatus);
                        }, 100);
                    })
                } else {
                    self.notifyPlayEffect(options, self.saveEffectStatus);
                }

            },

            saveEffectStatus: function (options) {
                var self = this;
                var entity = self.getEntity();

                Director.Dao.editEffect({id: options.eid, directorId: entity.id, status: options.status}, function (data) {
                    self.refreshEffectList(options.type);
                })
            },

            notifyPlayEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startplay';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request.directorId = options.did;
                request.logType = "114";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {

                    self.callback(options);
                })

            },

            stopPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();

                Director.Dao.editEffect({id: eid, directorId: entity.id, status: "0"}, function(data) {
                    self.refreshEffectList(type);
                })

            },

            submitStopPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();
                var options = {};

                options.eid = eid;
                options.pid = entity.programQipuId;
                options.type = type;
                options.status = "0";
                options.did = entity.id;

                //self.notifyStopPreviewEffect(options, function(options){});
                self.notifyStopPlayEffect(options, self.saveEffectStatus);

            },

            notifyStopPlayEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stopplay';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request.directorId = options.did;
                request.logType = "115";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {
                    self.callback(options);
                })
            },

            notifyStopPreviewEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request}, function (json) {
                    self.callback(options);
                })
            },

            notifyStopPreviewEffectByFlash: function (id) {
                var self = this;
                var entity = self.getEntity();

                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                request.params = {
                    ID: id,
                    PID: entity.programQipuId
                };
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request}, function (json) {
                })
            },
            notifySetResourcePlayCounts: function (data) {
                var self = this;
                var request = {};
                if (data != null && data.resourceId != null && data.num != null) {
                    request.id = data.resourceId;
                    request.playCounts = data.num;
                    Director.Dao.setResourcePlayCounts({id: data.resourceId, playCounts: data.num}, function (json) {

                    });
                }

            },

            isValidImage: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["png", "jpg", "bmp", "gif"]) >= 0;
            },

            isValidVideo: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["mov"]) >= 0;
            },

            isValidAudio: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["mp3"]) >= 0;
            },

            previewEffect: function (e) {
                var self = this;
                var eid = $(e).attr('data-id');
                var parent = $('#tabPanel_3');
                var curDiv = parent.find("div[data-div-id=" + eid + "]");
                var data = decodeURIComponent($(curDiv).attr('data'));
                Director.Player.addEffect(data);

                var btn = $('#effectBtnEdit');
                var isEditing = btn.attr('data-is-editing');
                if (isEditing == "0") {
                    btn.text("预览");
                    btn.attr('data-is-editing', "1");
                }

            },

            previewAnimationEffect: function (e) {
                var self = this;
                var eid = $(e).attr('data-id');

                var updateData = {
                    id: eid,
                    isPreview: 1
                };

                Director.Dao.editEffect(updateData, function (data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "预览成功", type: "success"});
                    } else {
                        EpgWeb.Plugin.showTips({content: "预览失败", type: "error"});
                    }
                });

            },

            closePreviewEffectReset: function () {
                Director.Player.closeEditEffect(0);

                var btn = $('#effectBtnEdit');
                var isEditing = btn.attr('data-is-editing');

                if (isEditing == "1") {
                    btn.text("编辑");
                    btn.attr('data-is-editing', "0");
                }
            },

            editPreviewEffectSwitch: function (e) {
                var btn = $(e);
                var isEditing = btn.attr('data-is-editing');

                if (isEditing == "0") {
                    Director.Player.openEditEffect();
                    btn.text("预览");
                    btn.attr('data-is-editing', "1");
                } else {
                    Director.Player.closeEditEffect(1);
                    btn.text("编辑");
                    btn.attr('data-is-editing', "0");
                }

            },

            notifyFlashEditEffect: function (e) {
                Director.Player.editEffect(e);
            },

            batchStopPreview: function (data, handler) {
                console.log('batchStopPreview ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();

                $.each(dataList, function (i, element) {
                    requestData = {
                        url: Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview',
                        type: 'get',
                        params: {
                            ID: element.id,
                            PID: entity.programQipuId
                        }
                    };
                    dataArr.push({'request': JSON.stringify(requestData), timeSign: currentTime});
                });

                var task = {
                    regName: "stopPreview",
                    options: {
                        url: '/api/redirect',
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);

                        handler.call(this, data);
                    }
                };


                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            batchStartPreview: function (data, handler) {
                console.log('batchStartPreview ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();

                $.each(dataList, function (i, element) {
                    requestData = {
                        url: Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startpreview',
                        type: 'get',
                        params: {
                            ID: element.id,
                            PID: entity.programQipuId
                        }
                    };
                    dataArr.push({'request': JSON.stringify(requestData), timeSign: currentTime});
                });

                var task = {
                    regName: "startPreview",
                    options: {
                        url: '/api/redirect',
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);

                        handler.call(this, data);
                    }
                };


                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            batchEditEffect: function (data, handler) {
                //console.log('batchEditEffect ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();
                var updateData = null;
                $.each(dataList, function (i, element) {
                    element.extraInfo.size = JSON.stringify(element.extraInfo.size);
                    updateData = {
                        id: element.id,
                        location: element.location,
                        extraInfo: JSON.stringify(element.extraInfo),
                        directorId: entity.id,
                        isPreview: 1
                    };
                    dataArr.push(updateData);
                });

                var task = {
                    regName: "editEffect",
                    options: {
                        url: Director.urlConfig.effectEditUrl,
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);
                        handler.call(this, data);
                    }
                };
                console.log("" + EpgWeb.ajaxQueue.isRunning());
                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            submitPreviewAllEffects: function (data) {
                var self = this;
                var actionNext = function () {
                    $(document).dequeue("previewEffects");
                };

                var dataList = JSON.parse(data);

                var actions = [];
                var entity = self.getEntity();

                $.each(dataList, function (i, element) {

                    // edit effect
                    actions.push(function () {
                        element.extraInfo.size = JSON.stringify(element.extraInfo.size);
                        var updateData = {
                            id: element.id,
                            location: element.location,
                            extraInfo: JSON.stringify(element.extraInfo),
                            directorId: entity.id,
                            isPreview: 1
                        };

                        Director.Dao.editEffect(updateData, function (data) {
                            if (data != null && data.code == "A00000") {
                                actionNext();
                            } else {
                                console.log('failed ' + data);
                            }
                        });
                    });

                    // stop preview
                    //actions.push(function() {
                    //    var request = {};
                    //
                    //    request.type = 'get';
                    //    request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                    //    request.params = {
                    //        ID: element.id,
                    //        PID: entity.programQipuId
                    //    };
                    //    request = JSON.stringify(request);
                    //    Ancestor.Dao.redirectRequest({request: request}, function(json) {
                    //        actionNext();
                    //    })
                    //})
                    //
                    //// start Preview
                    //actions.push(function() {
                    //    var request = {};
                    //
                    //    request.type = 'get';
                    //    request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startpreview';
                    //    request.params = {
                    //        ID: element.id,
                    //        PID: entity.programQipuId
                    //    };
                    //    request = JSON.stringify(request);
                    //    Ancestor.Dao.redirectRequest({request: request}, function(json) {
                    //        actionNext();
                    //    })
                    //})
                })

                actions.push(function () {
                    Director.Util.refreshEffectList(1);
                    Director.Util.refreshEffectList(2);
                    Director.Util.refreshEffectList(5);
                })


                $(document).queue("previewEffects", actions);
                actionNext();

            },

            dialogSubtitlePreview: function () {
                var parent = $('#dlg_edit_subtitle');
                var content = parent.find("textarea[name=content]");
                var fontName = parent.find('select[name=fontName]');
                var fontSize = parent.find('select[name=fontSize]');
                var fontColor = parent.find('input[name=fontColor]');
                var fontBold = parent.find('input[name=fontBold]');

                var styles = {
                    "font-family": fontName.find('option:selected').text(),
                    "font-size": fontSize.val() + "px",
                    "line-height": fontSize.val() + "px",
                    "font-weight": fontBold.val() == "1" ? "bold" : "normal",
                    "color": fontColor.val()
                }

                content.css(styles);

            },

            textLimit: function (e, limit, isNewline) {
                //if($(e).val().length > limit) {
                //    $(e).val($(e).val().substring(0, limit));
                //}
                console.log(e);
            },

            verifyForm: function (data, type) {
                var self = this;
                var checkArr = [];
                switch (type) {
                    case 1:
                        checkArr.push({value: [data.enterDuration, data.stayDuration, data.exitDuration, data.location_x, data.location_y],
                            error: ["进入时间只能为非负整数", "停留时间只能为非负整数", "退出时间只能为非负整数", "坐标只能为非负整数", "坐标只能为非负整数"], type: "number"});
                        checkArr.push({value: data.size_w, error: "大小为数字", type: "number"});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "le", other: 640});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "ge", other: 2});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 2:
                        checkArr.push({value: data.content, error: "请输入字幕内容", type: "not_empty"});
                        checkArr.push({value: Com.string.getStrLength(data.content), error: "字幕内容不能超过200个字", type: "le", other: 400});
                        checkArr.push({value: [data.location_x, data.location_y], error: "坐标只能为非负整数", type: "number"});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 3:
                        checkArr.push({value: data.url, error: "请上传动画", type: "not_empty"});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 5:
                        checkArr.push({value: [data.location_x, data.location_y],
                            error: ["坐标只能为非负整数", "坐标只能为非负整数"], type: "number"});
                        checkArr.push({value: data.size_w, error: "大小为数字", type: "number"});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "le", other: 640});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "ge", other: 2});
                        break;
                }
                if (checkArr.length > 0) {
                    return EpgWeb.Plugin.Validate.batchCheck(checkArr);
                }
                return true;
            },

            dataIsNumber: function (value) {
                return !isNaN(value)
            },

            strlen: function (str) {
                var len = 0;
                for (var i = 0; i < str.length; i++) {
                    var c = str.charCodeAt(i);
                    //单字节加1
                    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                        len++;
                    }
                    else {
                        len += 2;
                    }
                }
                return len;
            },

            isValidImageWidthHeight: function (url) {
                var image = new Image();
                image.onload = function () {
                    alert(image.width);
                }

                image.src = url;
                return false;

            },
            quickCreatePreviewUrl: function () {
                var parent = $("#dlg_add_signal");
                var signalUrl = parent.find("input[name=signal_url_2]").val();
                if (!this.checkValidStreamUrl(signalUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                    EpgWeb.Plugin.showTips({content: "流地址格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                    return false;
                }
                parent.find("button[name=query_system_preview_url]").prop("disabled", "disabled");
                parent.find("input[name=preview_url]").val("");
                parent.find("input[name=preview_url]").prop("readonly", true);
                Director.Dao.quickCreatePreviewUrl({url: signalUrl }, function (data) {
                    parent.find("input[name=preview_url]").removeAttr("readonly");
                    parent.find("button[name=query_system_preview_url]").removeAttr("disabled");
                    if (data != null && data.code == "A00000") {
                        parent.find("input[name=preview_url]").val(data.data)
                    } else {
                        parent.find("input[name=preview_url]").val("error happened")
                    }
                });
            },

            bindEffectImageEvent: function () {
                var self = this;
                var $imageArea = $("#effect-tabs-1");
                //$subtitleArea = $("#effect-tabs-2"),
                //$animationArea = $("#effect-tabs-3"),
                //$audioArea = $("#effect-tabs-4");

                var $imageUploadBtn = $imageArea.find("input.uploadBtn");
                var imageParent = $("#dlg_edit_image");
                $imageUploadBtn.val("");
                $imageUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $imageUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是图片
                    if (!Director.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式只支持png, jpg, bmp, gif, 请重新上传", type: "error"})
                        return;
                    }


                    self.startUploadFile(params, self.AddEffectImage);

                });
            },

            bindEffectAudioEvent: function() {
                var self = this;
                var $audioArea = $("#effect-tabs-4");

                var $audioUploadBtn = $audioArea.find("input.uploadBtn");
                $audioUploadBtn.val('');
                $audioUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $audioUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "audio";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是音频
                    if (!Director.Util.isValidAudio(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传音频格式只支持mp3, 请重新上传", type: "error"})
                        return;
                    }

                    self.startUploadFile(params, self.AddEffectAudio);

                });
            },

            AddEffectImage: function (data, params) {
                var self = this;
                var element = Director.Config.EFFECT_DEFAULTS['image'];

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 1;
                element.name = params.file.name;

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(1);
                    }
                })
            },

            AddEffectAudio: function (data, params) {
                var self = this;
                var element = {};

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 4;
                element.name = params.file.name;
                element.location = '';
                element.extraInfo = '{"volumn":20}';

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(4);
                    }
                })
            },

            setDirectorMainResource: function (mainResourceId) {
                var entity = this.getEntity();
                if (mainResourceId != null) {
                    Director.Dao.setDirectorMainResource({pid: entity.programQipuId, mainResourceId: mainResourceId}, function (data) {
                        if (data != null && data.code == "A00000") {
                            console.log("设置主信号源：" + data);
                            var elementDom = $("div[data-div-id=" + mainResourceId + "]");
                            if (typeof(elementDom) == "undefined"){
                                $("#imgLogo_mainResource").appendTo(Director.Config.ImgLogoMainResource);
                            } else {
                                $("#imgLogo_mainResource").appendTo(elementDom);
                            }
                            EpgWeb.Plugin.showTips({content: "设置成功"});
                        } else {
                            EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        }

                    });
                }
            },

        }
    )
});

define(
    '../director/Director.Commentary',['require','exports','module'],function (require, exports, module) {
        //解说 部分
        Director.Commentary = (function () {
            var maxLength = 8;
            var pageBean = new Director.Util.createPageBean();

            function getCommentaryList(needTips) {
                var entity = Director.Util.getEntity();
                Director.Dao.getCommentaryList({directorId: entity.id, programId: entity.programQipuId}, function (data) {
                    var container = $("#commentary_area");
                    if (data != null && data.code == "A00000" && data.data.length > 0) {
                        makeCommentaryList(data.data);
                        container.show();
                        if (needTips) {
                            EpgWeb.Plugin.showTips({content: "获取解说源成功", type: "success"});
                        }
                    } else {
                        container.hide();
                        if (needTips) {
                            EpgWeb.Plugin.showTips({content: "未发现可用的解说源", type: "error"});
                        }
                    }
                })
            }

            function makeCommentaryList(data) {
                var container = $("#commentary_area");
                var content = '';
                var htmlArr = [];
                pageBean.setNewData(data,maxLength);
                var pageObj = pageBean.getCur();
                $.each(pageObj.rows, function (index, e) {
                    htmlArr.push(makeUpCommentaryDiv(e));
                });

                content = htmlArr.join('');
                container.html(content);
                //if( data.length > maxLength){
                //    SystemDialog.queryAlert("解说数量超过"+maxLength+"个");
                //}
            }

            function clearCommentaryList() {
                var container = $("#commentary_area");
                container.html('');
                container.hide();
            }

            function makeUpCommentaryDiv(item) {
                var options = encodeURIComponent(JSON.stringify(item));
                var htmlArr = [];

                if ($.inArray(item.status, [0, 1, 2]) >= 0) {
                    htmlArr.push('<div class="commentary_div" data-div-id="' + item.id + '" data=' + options + '"><div>');
                    htmlArr.push('<object type="application/x-shockwave-flash" data="/epg/swfs/SignalSound.swf" width="280px" height="100%">');
                    htmlArr.push('<param name="scale" value="noscale"><param name="salign" value="tl">');
                    htmlArr.push('<param name="wmode" value="transparent"><param name="swliveconnect" value="true">');
                    htmlArr.push('<param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always">');
                    htmlArr.push('<param name="allownetworking" value="all"><param name="bgcolor" value="#000000">');
                    htmlArr.push('<param name="flashvars" value="resourceId=' + item.id + '&amp;status=' + item.status + '&amp;volumn=' + item.volumn + '&amp;rtmpUrl=' + item.streamUrl + '">');
                    htmlArr.push('</object></div>');
                    htmlArr.push('<h2 style="text-align: center;font-size:150%;">' + item.name + '</h2></div>');
                }

                return htmlArr.join("");

            }

            function refreshCommentaryList(needTips) {
                getCommentaryList(needTips);
            }


            function delCommentary(data) {
                var entity = Director.Util.getEntity();
                var eid = data['resourceId'];
                var sendData = {id: eid, directorId: entity.id};
                SystemDialog.queryConfirm("确定要删除么？", function (flag) {
                    if (flag == true) {
                        Director.Dao.deleteCommentary(sendData, function (json) {
                            if (json != null && json.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: "删除成功"});
                                Director.Commentary.refreshCommentaryList(false);
                            } else {
                                EpgWeb.Plugin.showTips({content: "删除失败 " + JSON.stringify(json), type: "error"});
                            }
                        })
                    }
                });
            }

            function playCommentary(data) {
                var entity = Director.Util.getEntity();
                var eid = data['resourceId'];
                var volumn = data['volumn'];

                var options = {
                    eid: eid,
                    did: entity.id,
                    pid: entity.programQipuId,
                    volumn: volumn
                };

                notifyChangeVolumn(options, function (options) {
                    notifyPlayCommentary(options, function (options) {
                        Director.Dao.editCommentary(
                            {id: options.eid, programId: options.pid, directorId: options.did, status: "1", volumn: options.volumn}, function (json) {
                                if (json != null && json.code == 'A00000') {
                                    EpgWeb.Plugin.showTips({content: "播出成功", type: "success"});
                                    //Director.Commentary.refreshCommentaryList(false);
                                } else {
                                    EpgWeb.Plugin.showTips({content: "播出失败 " + JSON.stringify(json), type: "error"});
                                }
                            })
                    })
                });
            }

            function notifyPlayCommentary(options, callback) {
                var handler = function () {
                    callback(options);
                }
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startcommentary';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };

                request.directorId = options.did;
                request.logType = "118";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {
                    if (json.error_code == 'A00000') {
                        handler();
                    } else {
                        EpgWeb.Plugin.showTips({content: "播出失败 " + JSON.stringify(json), type: "error"});
                    }
                    //self.callback(options);
                })
            }

            function stopCommentary(data) {
                var entity = Director.Util.getEntity();
                var eid = data['resourceId'];

                var options = {
                    eid: eid,
                    pid: entity.programQipuId,
                    did: entity.id
                };

                notifyStopCommentary(options, function (options) {
                    Director.Dao.editCommentary({id: options.eid, programId: options.pid, directorId: options.did, status: "0"}, function (json) {
                        if (json != null && json.code == 'A00000') {
                            EpgWeb.Plugin.showTips({content: "停止播出成功", type: "success"});
                            //Director.Commentary.refreshCommentaryList(false);
                        } else {
                            EpgWeb.Plugin.showTips({content: "停止播出失败 " + JSON.stringify(json), type: "error"});
                        }
                    })
                })
            }

            function notifyStopCommentary(options, callback) {
                var handler = function () {
                    callback(options);
                }
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stopcommentary';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request.directorId = options.did;
                request.logType = "119";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {
                    if (json.error_code == 'A00000') {
                        handler();
                    } else {
                        EpgWeb.Plugin.showTips({content: "停止播出失败 " + JSON.stringify(json), type: "error"});
                    }
                    //self.callback(options);
                })
            }

            function notifyChangeVolumn(options, callback) {
                var handler = function () {
                    callback(options);
                }
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'setcommentaryvolume';
                request.params = {
                    ID: options.eid,
                    PID: options.pid,
                    Volume: options.volumn
                };

                request.directorId = options.did;
                request.logType = "120";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {
                    if (json.error_code == 'A00000') {
                        handler();
                    } else {
                        EpgWeb.Plugin.showTips({content: "停止播出失败 " + JSON.stringify(json), type: "error"});
                    }
                    //self.callback(options);
                })
            }

            function changeCommentaryVolumn(data) {
                var entity = Director.Util.getEntity();
                var eid = data['resourceId'];
                var volumn = data['volumn'];

                var options = {
                    eid: eid,
                    pid: entity.programQipuId,
                    did: entity.id,
                    volumn: volumn
                };

                notifyChangeVolumn(options, function (options) {
                    Director.Dao.editCommentary({id: options.eid, programId: options.pid, directorId: options.did, volumn: options.volumn}, function (json) {
                        if (json != null && json.code == 'A00000') {
                            EpgWeb.Plugin.showTips({content: "设置音量成功", type: "success"});
                            //self.refreshCommentaryList(false);
                        } else {
                            EpgWeb.Plugin.showTips({content: "设置音量失败 " + JSON.stringify(json), type: "error"});
                        }
                    })
                })
            }

            function checkCommentaryAfterEditDirector() {
                var container = $("#commentary_area");
                if(container.html() != "") {
                    EpgWeb.Plugin.showTips({content: "配置已修改，请重新获取解说源。", type: "success"})
                }

            }

            return {
                getCommentaryList: getCommentaryList,
                makeCommentaryList: makeCommentaryList,
                makeUpCommentaryDiv: makeUpCommentaryDiv,
                refreshCommentaryList: refreshCommentaryList,
                delCommentary: delCommentary,
                changeCommentaryVolumn: changeCommentaryVolumn,
                stopCommentary: stopCommentary,
                playCommentary: playCommentary,
                clearCommentaryList: clearCommentaryList,
                checkCommentaryAfterEditDirector: checkCommentaryAfterEditDirector,
            }
        })()
    }
);
define(
    '../streamSearch/StreamSearch',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.StreamSearch = window.StreamSearch || {
                version: '1.0'
            };


    }
);

define(
    '../streamSearch/StreamSearch.Action',['require','exports','module'],function (require, exports, module) {
        StreamSearch.Action = (function () {
            var StreamGrid = null;

            var getStreamGrid = function (options) {
                if (!StreamGrid) {
                    StreamGrid = new StreamSearch.Grid($.extend(true, {
                        '$container': $('#StreamListContainer'),
                        type: 0
                    }, options));
                }

                return StreamGrid;
            }

            var StreamGridRun = function (options) {
                StreamGrid = getStreamGrid(options);
                StreamGrid.run();

                console.log('grid run');
            }

            var run = function () {
                Ancestor.Config.EPG_AUTH.list = '/stream/search';
                StreamGridRun({});
            }

            return {
                run: run,
                getStreamGrid: getStreamGrid
            }
        })();
    }
);
define('../streamSearch/StreamSearch.Config',['require','exports','module'],function(require, exports, module) {
    StreamSearch.Config = $.extend({}, Ancestor.Config, {


        // 编码状态
        STATUS: {},

        // 码流清晰度
        TYPE: {},

        // 地区
        DEST: {},

        CUTTER_ID: {
            FLV: [],
            TS: []
        },

        TABLE_COLMODEL_CONFIG: {
            /*
             id: {                    name: 'id',
             index:'id',
             title: false,
             width: 50,
             align: 'center',
             sortable: false
             },*/
            channelName: {
                name: 'channelName',
                index: 'channelName',
                title: false,
                width: 100,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return StreamSearch.Util.formatter.channelName(v, r);
                }
            },
            streamName: {
                name: 'streamName',
                index: 'streamName',
                width: 150,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamName(v, r);
                }
            },

            streamIp: {
                name: 'streamIp',
                index: 'streamIp',
                width: 90,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamIp(v, r);
                }

            },

            encodedIp: {
                name: 'encodedIp',
                index: 'encodedIp',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.encodedIp(v, r);
                }
            },

            inputSignal: {
                name: 'inputSignal',
                index: 'encodedIp',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return Stream.Util.formatter.inputSignal(v, r);
                }
            },

            dolbySignal: {
                name: 'dolbySignal',
                index: 'dolbySignal',
                width: 80,
                title: false,
                align: 'center',
                sortable: false,
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.dolbySignal(v, r);
                }
            },

            //dest: {
            //    name: 'dest',
            //    index: 'dest',
            //    width: 40,
            //    title: false,
            //    align: 'center',
            //    sortable: false,
            //    formatter: function(v, o, r) {
            //        return Stream.Util.formatter.dest(v, r);
            //    }
            //},

            streamType: {
                name: 'streamType',
                index: 'streamType',
                title: false,
                width: 60,
                sortable: false,
                align: 'center',
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.streamType(v, r);
                }

            },

            status: {
                name: 'status',
                index: 'status',
                title: false,
                width: 60,
                sortable: false,
                align: 'center',
                formatter: function(v, o, r) {
                    return Stream.Util.formatter.status(v, r);
                }

            },

            bitRate: {
                name: 'bitRate',
                index: 'bitRate',
                title: false,
                width: 60,
                align: 'center',
                sortable: false
            },

            inputBits: {
                name: 'inputBits',
                index: 'inputBits',
                title: false,
                width: 75,
                align: 'center',
                sortable: false
            },


            outputBits: {
                name: 'outputBits',
                index: 'outputBits',
                title: false,
                width: 80,
                align: 'center',
                sortable: false
            },


            aspectRatio: {
                name: 'aspectRatio',
                index: 'aspectRatio',
                title: false,
                align: 'center',
                width: 65
            },

            frameRate: {
                name: 'frameRate',
                index: 'frameRate',
                title: false,
                align: 'center',
                width: 45
            },

            screenSize: {
                name: 'screenSize',
                index: 'screenSize',
                title: false,
                sortable: false,
                align: 'center',
                width: 75

            },
            encodeType: {
                name: 'encodeType',
                index: 'encodeType',
                title: false,
                width: 70,
                align: 'center',
                sortable: false,

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.encodeType(v, r);
                }
            },

            audio: {
                name: 'audio',
                index: 'audio',
                title: false,
                width: 70,
                align: 'center',
                sortable: false
            },

            peerCount: {
                name: 'peerCount',
                index: 'peerCount',
                width: 40,
                sortable: false,
                align: 'center',
                title: false
            },

            addTime: {
                name: 'addTime',
                index: 'addTime',
                width: 120,
                sortable: false,
                align: 'center',
                title: false
            },

            updateTime: {
                name: 'updateTime',
                index: 'updateTime',
                width: 120,
                sortable: false,
                align: 'center',
                title: false
            },
            isEnable: {
                name: 'isEnable',
                index: 'isEnable',
                width: 75,
                sortable: false,
                align: 'center',

                formatter: function(v, o, r) {
                    return Stream.Util.formatter.isEnable(v, r);
                }
            },

        },


        TABLE: { //素材库查询列表配置
            url: '/api/stream/search',

            loadBeforeSend: function(xhr, settings) {
                var auth = Ancestor.Util.getAuth(Ancestor.Config.EPG_AUTH.list);
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },

            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,

            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },

            //datatype:"jsonp",
            multiselect: false,
            colNames: ["频道名称", "流名称", "RTMP地址", "编码器地址", "信号源", "杜比信号源", "清晰度", "编码状态",
                "码流", "推流流速率", "下载流速率", "画面比例", "帧率",
                "画面尺寸", "视频类型", "音频类型", "镜像服务器数", "添加时间", "最后更新时间", "上下线状态"
            ],

            colModel: ['channelName', 'streamName', 'streamIp', 'encodedIp', 'inputSignal','dolbySignal', 'streamType', 'status',
                'bitRate', 'inputBits', 'outputBits', 'aspectRatio', 'frameRate', 'screenSize', 'encodeType', 'audio',
                'peerCount', 'addTime', 'updateTime', 'isEnable'
            ]
        },


        // 流列表信息
        STREAMS_INFO: {},

        // 频道信息
        CHANNEL_INFO: null,

    });
});


define(
    '../streamSearch/StreamSearch.Dao',['require','exports','module'],function (require, exports, module) {

        StreamSearch.Dao = $.extend({}, Ancestor.Dao, {

        });
    }
);

define(
    '../streamSearch/StreamSearch.Grid',['require','exports','module'],function (require, exports, module) {
        StreamSearch.Grid = function (options) {
            this.dao = StreamSearch.Dao;
            this.config = StreamSearch.Config;
            this.options = options || {};
        };

        Com.inherits(StreamSearch.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
            },


            initConfigOfType: function (options) {

                Ancestor.Dao.getType({
                    type: options.sn
                }, function (json) {
                    if (json.code == 'A00000') {
                        var config = Stream.Config[options.sk];
                        if (options.sn == 'RtmpLocation') {
                            config[''] = '';
                        }

                        $.each(json.data, function () {
                            if (options.sn == 'StreamType' || options.sn == 'RtmpLocation')
                                config[this.val] = this.descr;
                            else
                                config[this.key] = this.descr;
                        });

                    } else {
                        console.log('fail!');
                    }

                    if (typeof(options.requestLoaded) == 'function') {
                        options.requestLoaded();
                    }

                });
            },

            run: function () {
                var self = this;
                this.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequest) {
                        self.initConfigOfType({
                            'sn': 'StreamType',
                            'sk': 'TYPE',
                            requestLoaded: ajaxBasicRequest
                        });
                    }
                });

                this.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequest) {
                        self.initConfigOfType({
                            'sn': 'StreamStatus',
                            'sk': 'STATUS',
                            requestLoaded: ajaxBasicRequest
                        });
                    }
                });

                this.ajaxBasicRequestManage.init(this, function (obj) {
                    obj.start();
                });
            },

            start: function (options, callback) {
                var self = this,
                    gridConfig = self.getGridConfig();

                self.init();

                self.echoQuery();
                options = $.extend(true, {
                    // width: 1500,
                    shrinkToFit: false
                    // autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
            },

            initGrid: function (options, callback) {
                var self = this;

                var gridConfig = self.getGridConfig();

                var $gridContainer = self.options.$container;

                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                    postData: {
                        streamName: ""
                    },
                    multiselect: true,
                    multiselectWidth: 30

                }, gridConfig, options);


                //$grid.jqGrid('scroll', {});
                $grid.jqGrid(options);

                var params = $grid.jqGrid("getGridParam");
                params.rowNum = 20;
                params.pages = 1;

            },

            query: function () {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                //params.fatherId = 10117;

                //StreamSearch.Config.TABLE.jsonReader = {
                //    root: "data.result",
                //    page: "data.pageNo",
                //    total: "data.totalCount/data.pageSize",
                //    records: "data.totalCount"
                //};

                $grid.jqGrid('setGridParam', {
                    postData: params
                }).trigger('reloadGrid', [
                    {
                        page: 1
                    }
                ]);

            },

            getParam: function () {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';

                    }

                });

                return params;

            },

            bindEvent: function () {
                var self = this;
                self.bindBasicEvent();
            },

            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function () {
                    self.query();
                    return false;
                });

                $form.find('button[type="reset"]').click(function() {
                    self.resetQueryForm();
                });

                $form.find('input[name=streamName]').keydown(function(e){
                    if(e.keyCode==13){
                        self.query();
                    }
                })
            },

            bindFormEvent: function ($form) {
            }

        })
    }
)
;
define('../streamSearch/StreamSearch.Util',['require','exports','module'],function (require, exports, module) {


    StreamSearch.Util = $.extend(true, {}, Ancestor.Util, {
        formatter: {
            channelName: function(v, r) {
                return '<a href="/epg/channel.html?channelName=' + r.channelName + '" target="_blank">' + r.channelName + '</a>';
            }
        }
    });

});


define(
    '../sysConfig/SysConfig',['require','exports','module'],function (require, exports, module) {
        window.SysConfig = window.SysConfig || {
            version: '1.0'
        };
        SysConfig.Constant = {
            baseApiUrl: (auth.dev() ? "http://10.23.70.33:7004/" : "http://dot.live.qiyi.domain/"),

            devMode: auth.dev()
        }

        SysConfig.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var addUrl = useUrl + "configs/add";
            var editUrl = useUrl + "configs/edit";
            var queryUrl = useUrl + "configs/query";
            return {
                addUrl: addUrl,
                editUrl: editUrl,
                queryUrl: queryUrl
            }
        })();
    }
);
define(
    '../sysConfig/SysConfig.Action',['require','exports','module'],function (require, exports, module) {
        SysConfig.Action = (function () {
            var listGrid = null;
            var listRun = function () {
                if (!listGrid) {
                    listGrid = new SysConfig.Grid($.extend(true, {
                        // '$container': $('#ChannelListContainer'),
                        type: 0
                    }, {}));
                }
                listGrid.runList();
                console.log('SysConfig grid run');
            }
            return {
                listRun:listRun
            }
        })();
    }
);

///import js-src/lib/
///import js-src/com/
define('../sysConfig/SysConfig.Config',['require','exports','module'],function (require, exports, module) {
    SysConfig.Config = $.extend({}, Ancestor.Config, {
        TABLE_COLMODEL_CONFIG:{
            type:{
                name: "type",
                index: 'type',
                title: false,
                sortable: false,
                width: 150
            },
            key:{
                name: "key",
                index: 'key',
                title: false,
                sortable: false,
                width: 60
            },
            val:{
                name: "val",
                index: 'val',
                title: false,
                sortable: false,
                width: 180
            },
            descr:{
                name: "desc",
                index: 'desc',
                title: false,
                sortable: false,
                width: 300
            },
            status:{
                name: "status",
                index: 'status',
                title: false,
                sortable: false,
                align: 'center',
                width: 60,
                formatter: function (v, o, r) {
                    return SysConfig.Util.formatter.status(v, o, r);
                }
            },
            operator_config:{
                title: false,
                width: 105,
                align: 'center',
                sortable: false,
                formatter: function (v, o, r) {
                    return SysConfig.Util.formatter.operator_config(v, o, r);
                }
            }
        },
        TABLE_LIST:{
            multiselect: false,
            datatype: "local",
            loadtext: '加载中...',
            localReader: {
                id: "id",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            rowNum:40,
            colModel:["type","key","val","descr","status","operator_config"],
            colNames:["类型", "索引", "值", "描述","启用状态","操作"],
            pager: "#pager",
            onPaging: function (pgButton) {
                var retValue = SysConfig.Util.pageBeanPageHandler("list", "pager", SysConfig.Config.PageBean, pgButton);
                if (retValue != null) {
                    $("#list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        SORT_RULE:{
            asc_type_key:function(a, b) {
                if(a.type == b.type){
                    return  a.key > b.key ? 1 : -1
                }
                return a.type > b.type ? 1 : -1
            }
        }
    })
});
define(
    '../sysConfig/SysConfig.Dao',['require','exports','module'],function (require, exports, module) {
        SysConfig.Dao = $.extend({}, EpgWeb.Dao, {
            submitEdit:function(data,callback){
                var options = {
                    type: "post",
                    url: SysConfig.urlConfig.editUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/configs/edit");
            },
            submitAdd:function(data,callback){
                var options = {
                    type: "post",
                    url: SysConfig.urlConfig.addUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/configs/add");
            },
            doQuery:function(data,callback){
                var options = {
                    type: "get",
                    url: SysConfig.urlConfig.queryUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/configs/query");
            }
        })
    }
);
define(
    '../sysConfig/SysConfig.Grid',['require','exports','module'],function (require, exports, module) {
        SysConfig.Grid = function (options) {
            this.dao = SysConfig.Dao;
            this.config = SysConfig.Config;
            this.options = options || {};
        };
        Com.inherits(SysConfig.Grid, Ancestor.Grid).extend({
            runList: function () {
                var self = this;
                self.$grid = $('#list');
                self.initDialog();
                self.initListGrid();
                self.bindEvent();
                self.config.PageBean = SysConfig.Util.createPageBean();
                self.query();
            },
            getParam:function(){
                var self = this;
                var $container = $("#QueryContainer");

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';

                    }

                });

                if(params['type'] != '') {
                    params.type = '%' + params.type + '%';
                }

                if(params['descr'] != '') {
                    params.descr = '%' + params.descr + '%';
                }

                return params;
            },

            verifyParams: function(params) {
                return true;
            },

            initDialog:function(){
                $("#edit-dlg").dialog({
                    title: "编目",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 500,
                    modal: true
                })
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initListGrid: function (options, callback) {
                var self = this;
                // var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function () {
                var self = this;
                var params = self.getParam();
                if(!self.verifyParams(params)) {
                    return;
                }

                self.dao.doQuery(params, function (data) {
                    var retValue = null;
                    if (data.code === "A00000" && data.data != null ) {
                        data.data.sort(SysConfig.Config.SORT_RULE.asc_type_key);
                        self.config.PageBean.setNewData(data.data,40);
                    } else {
                        self.config.PageBean.setNewData([]);
                    }
                    retValue = self.config.PageBean.goToFirst();
                    self.$grid[0].addJSONData(retValue)

                });
            },
            bindEvent: function() {
                var self= this;
                self.bindBasicEvent();

            },
            bindBasicEvent: function() {
                var self = this;
                var $container = $("#QueryContainer");
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function () {
                    self.query();
                    return false;
                });

                //$form.find('button[type="reset"]').click(function() {
                //    self.resetQueryForm();
                //});

                //$form.find('input[name=streamName]').keydown(function(e){
                //    if(e.keyCode==13){
                //        self.query();
                //    }
                //})
            },

            bindFormEvent: function() {

            }
        })
    }
);
define('../sysConfig/SysConfig.Util',['require','exports','module'],function (require, exports, module) {
    SysConfig.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operator_config:function (cellvalue, options, rowObject){
                return '<a href="javascript:;" onclick="SysConfig.Util.openEditView(' + rowObject.id + ' )">修改</a>' ;
            },
            status:function (cellvalue, options, rowObject){
                if(cellvalue == 2){
                    return "启用"
                }else if(cellvalue ==1){
                    return "未启用"
                }else{
                    return "undefined:"+cellvalue
                }
            }
        },
        openEditView:function(elementId){
            $("#edit-dlg").dialog("open");
            var parentDiv = $("#addFrom");
            parentDiv[0].reset();
            parentDiv.find("input[name=id]").val(elementId);
            var entity = SysConfig.Config.PageBean.findData("id",elementId);
            parentDiv.find("input[name=type]").val(entity.type);
            parentDiv.find("input[name=type]").attr("disabled","disabled");
            parentDiv.find("input[name=key]").val(entity.key);

            parentDiv.find("input[name=val]").val(entity.val);
            parentDiv.find("input[name=desc]").val(entity.desc);
            parentDiv.find("input[name=status][value='"+entity.status+"']").prop("checked", true);
        },
        openAddView:function(){
            $("#edit-dlg").dialog("open");
            var parentDiv = $("#addFrom");
            parentDiv[0].reset();
            parentDiv.find("input[name=id]").val("-1");
            parentDiv.find("input[name=type]").removeAttr("disabled");
            parentDiv.find("input[name=key]").removeAttr("disabled");

        },
        doCancel:function(){
            $("#edit-dlg").dialog("close");
        },

        checkParams: function(params) {
            if(params['type'] == '') {
                EpgWeb.Plugin.showTips({type:"error",content:"请填写类型" })
                return false;
            }

            if(params['key'] == '' || isNaN(params['key'])) {
                EpgWeb.Plugin.showTips({type:"error",content:"请填写索引" })
                return false;
            }

            if(params['val'] == '') {
                EpgWeb.Plugin.showTips({type:"error",content:"请填写值" })
                return false;
            }

            if(params['desc'] == '') {
                EpgWeb.Plugin.showTips({type:"error",content:"请填写描述" })
                return false;
            }
            return true;
        },

        doSubmitElement:function(){
            var self= this;
            var params = getParam($("#addFrom"));

            if(!self.checkParams(params)) {
                return;
            }

            if(params.id < 0) {
                self.submitAdd(JSON.stringify(params));
            }else{
                self.submitEdit(JSON.stringify(params));
            }
        },
        submitEdit:function(element){
            SysConfig.Dao.submitEdit({data:element},function(data){
                if(data != null && data.code =="A00000" ){
                    $('#edit-dlg').dialog('close');
                    EpgWeb.Plugin.showTips({type:"success",content:data.msg })
                    location.reload();
                }else{
                    EpgWeb.Plugin.showTips({type:"error",content:data.msg })
                }
            })
        },
        submitAdd:function(element){
            SysConfig.Dao.submitAdd({data:element},function(data){
                if(data != null && data.code =="A00000" ){
                    $('#edit-dlg').dialog('close');
                    EpgWeb.Plugin.showTips({type:"success",content:data.msg })
                    location.reload();
                }else{
                    EpgWeb.Plugin.showTips({type:"error",content:data.msg })
                }
            })
        },
        PageBean: null

    });


});
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'epg', [
        "../lib/spectrum",
        "../ancestor/Ancestor",
        "../ancestor/Ancestor.Crop",
        "../ancestor/Ancestor.Config",
        "../ancestor/Ancestor.Util",
        "../ancestor/Ancestor.Grid",
        "../ancestor/Ancestor.Dao",
        "../ancestor/Ancestor.Upload",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../channel/Channel",
        "../channel/Channel.Action",
        "../channel/Channel.Config",
        "../channel/Channel.Dao",
        "../channel/Channel.Grid",
        "../channel/Channel.Task",
        "../channel/Channel.Edit",
        "../channel/Channel.Util",
        "../stream/Stream",
        "../stream/Stream.Action",
        "../stream/Stream.Config",
        "../stream/Stream.Dao",
        "../stream/Stream.Grid",
        "../stream/Stream.Util",
        "../statisticOcr/StatisticOcr2",
        "../statisticOcr/StatisticOcr2.Action",
        "../statisticOcr/StatisticOcr2.Config",
        "../statisticOcr/StatisticOcr2.Dao",
        "../statisticOcr/StatisticOcr2.Grid",
        "../statisticOcr/StatisticOcr2.Util",
        "../statisticAuto/StatisticAuto",
        "../statisticAuto/StatisticAuto.Action",
        "../statisticAuto/StatisticAuto.Config",
        "../statisticAuto/StatisticAuto.Dao",
        "../statisticAuto/StatisticAuto.Grid",
        "../statisticAuto/StatisticAuto.Util",
        "../statisticSty2/StatisticSty2",
        "../statisticSty2/StatisticSty2.Action",
        "../statisticSty2/StatisticSty2.Config",
        "../statisticSty2/StatisticSty2.Dao",
        "../statisticSty2/StatisticSty2.Grid",
        "../statisticSty2/StatisticSty2.Util",
        "../statisticSty2/StatisticSty2Percent",
        "../statisticSty2/StatisticSty2Percent.Action",
        "../statisticSty2/StatisticSty2Percent.Config",
        "../statisticSty2/StatisticSty2Percent.Dao",
        "../statisticSty2/StatisticSty2Percent.Grid",
        "../statisticSty2/StatisticSty2Percent.Util",
        "../preSet/PreSet",
        "../preSet/PreSet.Action",
        "../preSet/PreSet.Config",
        "../preSet/PreSet.Dao",
        "../preSet/PreSet.Edit",
        "../preSet/PreSet.Grid",
        "../preSet/PreSet.Util",
        "../news/News",
        "../news/News.Action",
        "../news/News.Config",
        "../news/News.Dao",
        "../news/News.Edit",
        "../news/News.Grid",
        "../news/News.Util",
        "../newsDetails/NewsDetails",
        "../newsDetails/NewsDetails.Action",
        "../newsDetails/NewsDetails.Config",
        "../newsDetails/NewsDetails.Dao",
        "../newsDetails/NewsDetails.Grid",
        "../newsDetails/NewsDetails.Util",
        "../newsStatistic/NewsStatistic",
        "../newsStatistic/NewsStatistic.Action",
        "../newsStatistic/NewsStatistic.Config",
        "../newsStatistic/NewsStatistic.Dao",
        "../newsStatistic/NewsStatistic.Grid",
        "../newsStatistic/NewsStatistic.Util",
        "../director/Director",
        "../director/Director.Action",
        "../director/Director.Config",
        "../director/Director.Dao",
        "../director/Director.Task",
        "../director/Director.Grid",
        "../director/Director.Edit",
        "../director/Director.Player",
        "../director/Director.Model",
        "../director/Director.Util",
        "../director/Director.Commentary",
        "../streamSearch/StreamSearch",
        "../streamSearch/StreamSearch.Action",
        "../streamSearch/StreamSearch.Config",
        "../streamSearch/StreamSearch.Dao",
        "../streamSearch/StreamSearch.Grid",
        "../streamSearch/StreamSearch.Util",
        "../sysConfig/SysConfig",
        "../sysConfig/SysConfig.Action",
        "../sysConfig/SysConfig.Config",
        "../sysConfig/SysConfig.Dao",
        "../sysConfig/SysConfig.Grid",
        "../sysConfig/SysConfig.Util"
    ],

    function() {
        console.log('epg load done:', 'epg');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }

);
